A list is an ordered, mutable collection. It can hold values of any type, including other lists.
fruits = ["apple", "banana", "cherry"]
numbers = [3, 1, 4, 1, 5]
mixed = [1, "two", 3.0, True, None]
empty = []The square brackets create the list. Commas separate the items.
Length and membership#
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) # 3
print("banana" in fruits) # True
print("grape" in fruits) # Falselen() returns the number of top-level items. Membership uses equality comparisons.
Indexing#
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[-1]) # cherry
print(fruits[-2]) # bananaA negative index counts from the end. Out-of-range indexes raise IndexError.
Slicing#
Slices return a new list:
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4]) # [1, 2, 3]
print(numbers[:3]) # [0, 1, 2]
print(numbers[3:]) # [3, 4, 5]
print(numbers[::2]) # [0, 2, 4]
print(numbers[::-1]) # [5, 4, 3, 2, 1]The stop index is excluded, just like string slicing.
Changing items#
Lists are mutable, so you can assign to an index or a slice:
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
fruits[0:1] = ["apricot", "avocado"]
print(fruits)['apricot', 'avocado', 'blueberry', 'cherry']
The slice assignment can change the list length.
Iteration#
scores = [72, 85, 91]
for score in scores:
print(score)Use enumerate() when you also need the position:
for index, score in enumerate(scores, start=1):
print(f"Student {index}: {score}")List comprehensions#
A list comprehension creates a new list from an iterable:
numbers = [1, 2, 3, 4, 5, 6]
squares = [number ** 2 for number in numbers]
evens = [number for number in numbers if number % 2 == 0]
print(squares)
print(evens)[1, 4, 9, 16, 25, 36] [2, 4, 6]
Keep comprehensions short. If the expression needs several steps, a normal loop is clearer.
Nested lists#
grid = [
[1, 2, 3],
[4, 5, 6],
]
print(grid[1][2]) # 6
for row in grid:
for value in row:
print(value, end=" ")
print()A nested list is often used for matrices, but each inner list is independent only if you create them separately.
Copying and references#
Assignment does not copy a list:
a = [1, 2, 3]
b = a
b.append(4)
print(a)[1, 2, 3, 4]
Both names refer to the same list. Make a shallow copy with a.copy(), a[:], or list(a). For nested lists, use copy.deepcopy() when you need independent inner objects.
Practice#
Create a list of five temperatures. Print the highest and lowest values, the average, and a new list containing only temperatures above the average. Then reverse the original list and print it.
