List
1. What is a List?
- A list in
Python is a collection of items (also called elements or values)
that are ordered and mutable (i.e., you can change their contents after
creation).
- Lists
can contain different data types such as integers,
floats, strings, or even other lists.
- Lists
are written using square brackets [], and the elements
are separated by commas.
fruits = ["apple", "banana",
"cherry"]
mixed_list = [1, "Hello", 3.5]
2. Creating and Accessing Lists
You can create a list by enclosing elements in square
brackets, and the elements can be of any type (integer, string, etc.).
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
Accessing list elements: You can
access the elements of a list using indexing (starting from 0 for the
first element).
fruits = ["apple", "banana",
"cherry"]
print(fruits[0])
Output: "apple"
print(fruits[2])
Output: "cherry"
Negative indexing allows
you to access elements from the end of the list:
print(fruits[-1])
Output: "cherry" (last
element)
print(fruits[-2])
Output: "banana" (second last
element)
3. Indexing and Slicing Lists
Indexing: Just like strings, list
elements can be accessed using their index positions.
my_list = [10, 20, 30, 40, 50]
print(my_list[1])
Output: 20
Slicing: Slicing allows you to retrieve
a subset of the list by specifying a range [start:end:step].- start:
the index where the slice begins (inclusive).
- end:
the index where the slice ends (exclusive).
- step:
how many elements to skip between each element.
my_list = [10, 20, 30, 40, 50, 60]
print(my_list[1:4])
Output: [20, 30, 40] (indexes 1 to 3)
print(my_list[:3])
Output: [10, 20, 30] (start from index
0)
print(my_list[3:])
Output: [40, 50, 60] (from index 3 to
end)
print(my_list[::2])
Output: [10, 30, 50] (every second
element)
Negative slicing: You can also use
negative numbers for slicing, starting from the end of the list.
print(my_list[-4:-1])
Output: [30, 40, 50]
4. List Methods
Python provides several built-in methods to
manipulate lists:
(a) .append(): Adds an element to the end of the list.
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
Output: ['apple', 'banana', 'cherry']
(b) .insert(): Inserts an element at a specific
position.
fruits.insert(1, "orange")
print(fruits)
Output: ['apple', 'orange', 'banana',
'cherry']
(c) .remove(): Removes the first occurrence of the
specified value.
fruits.remove("banana")
print(fruits)
Output: ['apple', 'orange', 'cherry']
(d) .pop(): Removes and returns the element at the
specified position (default is the last element if no index is given).
last_fruit = fruits.pop()
print(fruits)
Output: ['apple', 'orange']
print(last_fruit)
Output: 'cherry'
(e) .extend(): Extends the list by adding elements
from another list or iterable.
vegetables = ["carrot", "broccoli"]
fruits.extend(vegetables)
print(fruits)
Output: ['apple', 'orange', 'carrot',
'broccoli']
(f) .index(): Returns the index of the first
occurrence of the specified value.
print(fruits.index("apple"))
Output: 0
(g) .count(): Returns the number of times a
specified value occurs in the list.
print(fruits.count("apple"))
Output: 1
(h) .reverse(): Reverses the elements of the list
in place.
fruits.reverse()
print(fruits)
Output: ['broccoli', 'carrot', 'orange',
'apple']
(i) .sort(): Sorts the list in ascending order by
default.
numbers = [3, 1, 4, 1, 5]
numbers.sort()
print(numbers)
Output: [1, 1, 3, 4, 5]
(j) .clear(): Removes all elements from the list.
fruits.clear()
print(fruits)
Output: []
5. Nested Lists
A nested list is a list that contains other
lists as its elements.
nested_list = [[1, 2, 3], ["apple", "banana",
"cherry"], [10.5, 20.75]]
You can access elements of nested lists by using multiple
indices.
print(nested_list[0][1])
Output: 2 (second element of the first
list)
print(nested_list[1][2])
Output: "cherry" (third
element of the second list)
Nested lists can be useful for representing matrices or tables.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][1])
Output: 5 (element in the second row and
second column)
6. List Comprehension
List comprehension is
a concise way to create lists using a for-loop within square
brackets. It's more compact than traditional loops.
squares = [x**2 for x in range(5)]
print(squares)
Output: [0, 1, 4, 9, 16]
You can also include conditional statements in
list comprehension.
even_squares = [x**2 for x in range(10) if x % 2
== 0]
print(even_squares)
Output: [0, 4, 16, 36, 64]
Nested list comprehension: You can
generate complex lists using nested comprehensions.
matrix = [[j for j in range(3)] for i in range(3)]
print(matrix)
Output:
[[0, 1, 2],
[0, 1, 2],
[0, 1, 2]]