Lesson 17: Lists: the workhorse collection
A list holds many values in order and lets you change them. Append, insert, remove, pop and sort are the five methods that cover most work with lists.
In short
- A list is written with square brackets and keeps its order: `["apple", "banana"]`.
- Lists are mutable, so `append()`, `insert()`, `remove()` and `sort()` change the list in place.
- `pop()` removes and returns an item; `remove()` removes the first matching value and returns nothing.
- `sort()` changes the list, `sorted()` returns a new one — the same split applies to `reverse()`.
0
fixed size: a list grows as needed
Python docs
2
sorting options: sort() in place, sorted() a copy
Python docs
What a list is
A list is an ordered collection that can hold any values and can change after it is created. Square brackets create one, and commas separate the items.
fruits = ["apple", "banana", "cherry"]
marks = [45, 67, 89]
mixed = ["Asha", 21, True]
print(fruits)
print(marks)
print(mixed)
The program
# lists.py — the five methods that do most of the work
fruits = ["apple", "banana", "cherry"]
print(fruits[0], fruits[-1]) # apple cherry
print(fruits[1:]) # ['banana', 'cherry']
fruits.append("date") # adds at the end
fruits.insert(1, "blueberry") # adds at position 1
print(fruits)
print(fruits.pop()) # date, removed and returned
fruits.remove("banana") # removed by value
print(fruits)
numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers) # [1, 2, 5, 9]
numbers.sort(reverse=True)
print(numbers) # [9, 5, 2, 1]
print(len(numbers), 9 in numbers) # 4 True
How it works, step by step
fruits[0]is the first item,fruits[-1]the last. Negative indexes count backwards.fruits[1:]slices from position 1 to the end.append()adds one item to the end.insert(1, x)puts it at position 1 and shifts the rest along.pop()without an argument removes the last item and returns it, so you can store it.remove(value)finds the first matching item and deletes it. It returnsNone, and raisesValueErrorif the value is absent.sort()arranges the list in place, smallest first.reverse=Trueflips the order.
What it prints
apple cherry ['banana', 'cherry'] ['apple', 'blueberry', 'banana', 'cherry', 'date'] date ['apple', 'blueberry', 'cherry'] [1, 2, 5, 9] [9, 5, 2, 1] 4 True
The methods, side by side
| Method | Effect | Returns |
|---|---|---|
append(x) | Adds x at the end | None |
insert(i, x) | Adds x at position i | None |
extend(list) | Adds every item of another list | None |
remove(x) | Deletes the first x | None |
pop(i) | Deletes the item at i and returns it | the item |
sort() | Sorts in place | None |
reverse() | Reverses in place | None |
count(x), index(x) | Counts or finds x | a number |
Common mistakes
numbers = numbers.sort()setsnumberstoNone, because sort returns nothing. Callsort()on its own line.- Copying with
b = aand then changingb, which also changesa. Both names point at one list; usea.copy()ora[:]. - Removing items while looping over the same list. Loop over a copy.
Practice
Try these before moving on. Each one uses only what this lesson covered.
- Create a list of five subjects, add one at the end and one at position 1, then print the list.
- Remove one subject by value and one by position, and print what each call returned.
- Sort a list of marks in ascending and descending order and print both.
- Find the second largest number in a list of numbers.
Sources
Frequently asked questions
How do I add an item to a list in Python?
append(x) adds it at the end, insert(i, x) puts it at a position, and extend(other) adds everything from another list. All three change the list in place and return None.
What is the difference between remove() and pop()?
remove(value) deletes the first item with that value and returns nothing. pop(index) deletes the item at a position and returns it, which is useful when you need the value.
What is the difference between sort() and sorted()?
sort() rearranges the list itself and returns None. sorted(list) leaves the original untouched and returns a new sorted list.
How do I copy a list properly?
Use list.copy(), list[:] or list(list). A plain b = a only copies the reference, so a change through one name shows up in the other.