Python Foundations·Lesson 5 of 67·beginner
Lists
The ordered, mutable collection you will reach for more than any other — building it, changing it, slicing it, and knowing when it is the wrong tool.
In this lesson · 15 min
- →Create, index and slice lists
- →Add, remove, sort and reverse items
- →Understand that a list is a reference, not a copy
- →Write your first list comprehension
A list holds an ordered collection of anything, and unlike a string, you can change it in place.
Lists are heterogeneous — Python does not require the items to share a type:
In practice you almost always want a list of one kind of thing. A list of mixed types usually means the data should have been a dictionary.
Changing a list
Searching and counting
index raises a ValueError if the value is not there, so check with in first when you are
not sure.
Sorting
There are two ways, and the difference matters.
sorted() works on anything iterable and leaves the original alone. .sort() is a list method
that mutates. A common mistake is numbers = numbers.sort(), which sets numbers to None.
Sorting by a computed key is where it gets useful:
Slicing works exactly as it does on strings
A list is a reference
This catches everyone once. Assigning a list to a new name does not copy it.
Building lists with a loop — then without one
The long way:
The Python way — a list comprehension:
Read it left to right: the expression, for each item, if the condition holds. It is shorter, and — because Python does the looping internally — usually faster.
Try it yourself
Print the three highest scores in descending order, as a list.
Build passing: the names of every model scoring 0.85 or better, in the original order. Use a list comprehension.
Check yourself
After numbers = [3, 1, 2] and result = numbers.sort(), what is result?
Recap
- Lists are ordered, mutable and can hold anything.
appendadds one item,extendadds many,popremoves and returns.sorted(x)returns a new list;x.sort()mutates and returnsNone.- Assignment shares a list; use
x[:]orlist(x)to copy. - A list comprehension is the idiomatic way to build a list from another sequence.