Python Lists
Create, read, change, sort, and safely copy lists of values.
A list holds a sequence
A list stores values in order. Put items between square brackets, separated by commas.
Positions begin at 0. A negative position counts from the end.
colors = ['red', 'green', 'blue'] print(colors[0]) print(colors[-1]) print(colors[1:])
colors[0] is the first item. colors[-1] is the last item. The slice colors[1:] makes a new list from index 1 to the end.
Change a list
Lists are mutable, which means you can change them after creating them. You can assign to an index or use list methods.
pets = ['cat', 'dog']
pets[1] = 'parrot'
pets.append('fish')
pets.insert(1, 'hamster')
pets.extend(['lizard', 'ant'])
pets.remove('cat')
last_pet = pets.pop()
del pets[1]
print(pets)
print(last_pet)
append() adds one item, insert() adds at an index, and extend() adds every item from another sequence. remove() removes a matching value, pop() removes and returns an item, and del removes by index.
Order and copy lists
scores = [8, 3, 5] print(sorted(scores)) scores.sort() scores.reverse() copy_scores = scores.copy() copy_scores.append(10) print(scores) print(copy_scores) print(len(scores))
| Tool | What it does | Changes the list? |
|---|---|---|
| sorted(items) | Returns a sorted new list | No |
| items.sort() | Sorts the same list | Yes |
| items.reverse() | Reverses the same list | Yes |
| len(items) | Counts items | No |
Key points
- Lists use square brackets.
- Indexes start at zero; -1 is the last item.
- Lists can be changed with assignments and methods.
- sorted() returns a new list, while sort() changes one.
- Use list.copy() to avoid accidental aliasing.
Worked example
A Saturday market list grows and shrinks: add coriander, buy the aubergine off, count what is left.
basket = ["rice", "aubergine"]
basket.append("coriander")
basket.remove("aubergine")
print(basket, len(basket))
How it works, step by step
- append() adds to the END.
- remove() deletes the first matching VALUE (not position).
- len() counts current items.
References & Further Reading
Related entries from PyLabs's own reference library.
Practice exercise
Not passed yetCreate numbers = [4, 1, 3]. Append 2, sort the list in place, then print it.
Expected output: [1, 2, 3, 4]
# Write your code below
Check yourself
Python Lists quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.