Lists
A list is an ordered collection of values, written as items separated by commas inside square brackets. Lists can hold values of any type, even a mix of types, and are one of the most frequently used data structures in Python.
Creating a List
fruits = ["apple", "banana", "cherry"]
print(fruits)
print(len(fruits)) # 3, the number of items
Indexing and Slicing
Lists use exactly the same indexing and slicing syntax as strings.
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0]) # apple, the first item
print(fruits[-1]) # date, the last item
print(fruits[1:3]) # ['banana', 'cherry']
Lists Are Mutable
Unlike strings, lists can be changed after they are created — you can update, add, or remove items in place without creating a new list object.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry" # directly replaces "banana"
print(fruits) # ['apple', 'blueberry', 'cherry']
Common List Methods
| Method | Description | Example |
|---|---|---|
.append(x) | Adds an item to the end | fruits.append("mango") |
.insert(i, x) | Inserts an item at a specific index | fruits.insert(0, "kiwi") |
.remove(x) | Removes the first matching value | fruits.remove("apple") |
.pop() | Removes and returns the last item (or at a given index) | fruits.pop() |
.sort() | Sorts the list in place | fruits.sort() |
.reverse() | Reverses the order in place | fruits.reverse() |
numbers = [5, 3, 1, 4]
numbers.append(9) # [5, 3, 1, 4, 9]
numbers.sort() # [1, 3, 4, 5, 9]
numbers.reverse() # [9, 5, 4, 3, 1]
last = numbers.pop() # removes and returns 1
print(numbers, last)
List Comprehensions
A list comprehension is a compact, distinctly Pythonic way to build a new list from an existing sequence in a single line, instead of writing a full for loop with .append().
# the long way, with a regular for loop
doubled = []
for x in range(5):
doubled.append(x * 2)
print(doubled) # [0, 2, 4, 6, 8]
# the same result as a list comprehension
doubled = [x * 2 for x in range(5)]
print(doubled) # [0, 2, 4, 6, 8]
The general pattern is [expression for item in sequence]. You can add a condition at the end to filter which items are included:
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
Checking Membership
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # True
Nested Lists
Because a list can hold any type of value, including other lists, you can build a "list of lists" to represent grid-like or tabular data.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[0]) # [1, 2, 3], the first inner list
print(matrix[1][2]) # 6, second row, third column