Indexing
Indexes count from 0, and from -1 at the far end
First is a[0]. Last is a[-1]. Past the end: IndexError.
A list keeps its items in order, and each has a position. The positions start at zero, not one. So five items are numbered nought to four. Every item also has a negative position, counted from the right, starting at minus one. So a zero is ten, and a minus one is fifty: the last item, however long the list. There is no position five. Asking for it is an index error.
Indexing · Going deeper
Making a list
[] is empty. len(), in, +, *.
Slicing
A slice takes from start up to, not including, stop
a[start:stop:step]. The stop is left out.
A slice takes several items at once, as a new list. a one colon three starts at index one and stops before index three: twenty, thirty. Leave out the start, and it begins at the beginning. Leave out the stop, and it runs to the end. A third number is the step: every other item. And a step of minus one walks backwards, which reverses the list.
Slicing · Going deeper · 1 of 2
More slices
Negative counts from the end. a[:] is a copy.
Slicing · Going deeper · 2 of 2
A second name is not a copy
b = a: one list. a[:]: a new one.
Check yourself
What does this print?
Changing a list
A list can be changed in place
append(), insert(), del, and a[i] = .
Unlike a number or a string, a list can be altered after it is made. Start with three items. Append adds one at the end. Insert puts fifteen at index one, and everything after it moves up. Del removes the item at index nought. And assigning to an index replaces what is there. It is the same list throughout.
Changing a list · Going deeper
Searching a list
in, index(), len().
Sorting
sorted() gives a new list. .sort() changes yours.
sorted(a) returns a copy. a.sort() returns None.
There are two ways to sort, and the exam relies on you mixing them up. a is three, one, two. Sorted of a builds a new, sorted list for b. a is left exactly as it was. a dot sort sorts a itself. It gives nothing back, so c is None.
Sorting · Going deeper
Updating a list in a loop
Use the indexes: range(len(nums)).
Check yourself
What does this print?
Lists of lists
A list of lists needs one index for each level
m[row][column]. m[1] is a whole row.
The items of a list can themselves be lists. That gives you a table. Here m has two rows of three. One index picks a row: m one is the list four, five, six. A second index goes into that row: m one, zero, is four. The length of m is two: it has two items, each a list. The length of a row is three.
Lists of lists · Going deeper
Changing, looping, and a third level
Nested loop for two levels. c[1][0][1] for three.
Check yourself
What does this print?
Lesson complete
You finished “Lists”
Answer the questions along the way to see your score here.