Lists
A list is an ordered collection of items that you can change. Lists let one variable hold many values, such as all the names in a class, a week's expenses or the items in a shopping basket. They are the most widely used data structure in Python.
Creating a list
Write the items inside square brackets, separated by commas. A list can hold any type of value, even a mixture, and can be empty.
fruits = ["mango", "banana", "pawpaw", "orange", "avocado"] scores = [72, 85, 64, 90] profile = ["Amina", 20, True, 1.65] # mixed types are allowed empty = [] print(fruits) print(profile) print(len(fruits)) print(len(empty))
You can also build a list from another sequence with list(): list("Kuza") gives ['K', 'u', 'z', 'a'] and list(range(4)) gives [0, 1, 2, 3].
Accessing items: indexing and slicing
Lists use the same indexing and slicing rules as strings. The first item is at index 0, and negative indexes count from the end.
fruits = ["mango", "banana", "pawpaw", "orange", "avocado"] print(fruits[0]) print(fruits[-1]) print(fruits[1:3]) print(fruits[:2]) print(fruits[::2])
An index gives you one item; a slice always gives you a new list, even if it contains only one item.
fruits[0] and fruits[-5] name the same cell. The slice fruits[1:3] takes indexes 1 and 2 (highlighted) and stops before index 3.Using an index that doesn't exist. fruits[5] on a five-item list raises IndexError: list index out of range, because the valid indexes are 0 to 4. Remember: the last index is len(fruits) - 1.
Changing a list
Unlike strings, lists are mutable: you can change, add and remove items after the list is created.
fruits = ["mango", "banana", "pawpaw"]
fruits[1] = "pineapple" # replace an item
print(fruits)
fruits.append("guava") # add to the end
print(fruits)
del fruits[0] # delete by position
print(fruits)
append() is one of many list methods. The next page, List Methods, covers adding, removing, sorting and searching in detail.
Checking, combining and repeating
crops = ["maize", "beans"]
print("beans" in crops)
print("rice" not in crops)
print(crops + ["rice", "sorghum"])
print([0] * 4)
print([1, 2, 3] == [1, 2, 3])
+ creates a new list; crops itself is unchanged. == compares two lists item by item.
Looping and built-in functions
A for loop visits each item in order, and Python's built-in functions summarise a list of numbers in one step.
scores = [72, 85, 64, 90]
for score in scores:
print("Score:", score)
print("Total:", sum(scores))
print("Highest:", max(scores))
print("Lowest:", min(scores))
print("Average:", sum(scores) / len(scores))
Lists inside lists
An item in a list can itself be a list. This is how you represent tables and grids. Use two indexes: the first picks the row, the second picks the item in that row.
timetable = [
["Maths", "English", "Biology"], # Monday
["Chemistry", "History", "Maths"], # Tuesday
]
print(timetable[0])
print(timetable[1][2])
Looping through such grids is covered on Nested Loops.
Unpacking
You can assign a list's items to separate variables in one line, as long as the counts match.
name, county, age = ["Brian", "Kisii", 23] print(name, "from", county, "is", age)
Copying a list: the aliasing trap
Assigning a list to another variable does not copy it. Both names refer to the very same list, so a change through one name shows up through the other.
original = [1, 2, 3] alias = original # same list, two names alias.append(4) print(original) original = [1, 2, 3] copy = original.copy() # a separate list copy.append(4) print(original) print(copy)
Thinking b = a makes a copy. It only creates a second name for the same list (remember: variables are labels, as explained on Variables). To get an independent copy, use a.copy(), list(a) or a[:]. These make a shallow copy: lists inside the list are still shared.
Key points
- Lists are ordered, changeable collections written in square brackets.
- Index from 0 (or from -1 at the end); slices return new lists.
- Change items by index, add with
append()and delete withdel. len(),sum(),max(),min()andinwork directly on lists.b = ashares one list; usea.copy()for a separate copy.
Tip: use the ← and → keys to move between pages.
