Imagine you want to store the names of 30 students. You could create 30 separate variables — but that would be exhausting and impractical. A list solves this by storing multiple values inside a single variable, in order. In other programming languages this structure is often called an array.
Creating a List
fruits = ["apple", "banana", "cherry"]
scores = [85, 72, 91, 68, 77]
mixed = [1, "hello", True, 3.14]
empty = []
Lists use square brackets []. Items are separated by commas. A list can hold any type of data — even a mix of types.
Accessing Items
Items are accessed by their index, starting at 0:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[-1]) # cherry (last item)
Negative indices count from the end: -1 is the last item, -2 is second to last, and so on.
A list with 5 items has indices 0, 1, 2, 3, 4. Trying to access index 5 raises an IndexError. Always remember that the last valid index is len(list) - 1.
Modifying a List
Lists are mutable — you can change them after creation:
scores = [70, 80, 90]
scores[1] = 85 # change index 1
print(scores) # [70, 85, 90]
Adding and Removing Items
| Method | What it does | Example |
|---|---|---|
.append(x) | Adds x to the end | scores.append(95) |
.insert(i, x) | Inserts x at position i | scores.insert(0, 60) |
.remove(x) | Removes first occurrence of x | scores.remove(80) |
.pop() | Removes and returns last item | last = scores.pop() |
.pop(i) | Removes item at index i | scores.pop(2) |
Useful List Operations
numbers = [4, 1, 9, 2, 7, 3]
print(len(numbers)) # 6
print(min(numbers)) # 1
print(max(numbers)) # 9
print(sum(numbers)) # 26
print(sorted(numbers)) # [1, 2, 3, 4, 7, 9]
print(9 in numbers) # True
in is a very clean way to check whether a value exists in a list. if "apple" in fruits: reads almost like plain English.
Iterating Over a List
The most common way to process every item in a list is a for loop:
students = ["Alice", "Bob", "Carlos", "Diana"]
for student in students:
print(f"Hello, {student}!")
If you also need the index, use enumerate():
for i, student in enumerate(students):
print(f"{i + 1}. {student}")
List Slicing
Just like strings, lists support slicing:
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[2:]) # [30, 40, 50]
When you do b = a with a list, both variables point to the same list in memory. Changing b will also change a. To create an independent copy, use b = a[:] or b = a.copy().
Practice Problems
Given colours = ['red', 'green', 'blue'], how do you add 'yellow' to the end and then remove 'green'?
Show answer
What is the difference between a list and a string in Python? Name one thing they have in common.