Indexing

Indexes count from 0, and from -1 at the far end

a = [10, 20, 30, 40, 50]100201302403504-5-4-3-2-1a[0] is 10a[-1] is 50a[5] is an IndexErrorIndexes count from 0, and from -1 at the far end.A list of 5 items has indexes 0 to 4. The last item is a[4], and also a[-1], which savescounting. An index past either end is an IndexError, raised when that line runs.

First is a[0]. Last is a[-1]. Past the end: IndexError.

Indexing · Going deeper

Making a list

CodeGivesNote[][]An empty list; its length is 0[1, 'a', 2.5, True][1, 'a', 2.5, True]Items may be of different typeslen([10, 20, 30])3The number of items[1, 2] + [3][1, 2, 3]+ joins two lists into a new one[0] * 3[0, 0, 0]* repeats a list30 in [10, 20, 30]Truein asks whether a value is there5 not in [10, 20]Truenot in asks the oppositeA list is an ordered collection that can change.Square brackets make one, with commas between the items. Order is kept, and repeats are allowed.

[] is empty. len(), in, +, *.

Slicing

A slice takes from start up to, not including, stop

100201302403504a[1:3][20, 30]from index 1 up to, not including, 3a[:2][10, 20]no start: from the beginninga[3:][40, 50]no stop: to the enda[::2][10, 30, 50]a step of 2: every other itema[::-1][50, 40, 30, 20, 10]a step of -1: reversedA slice takes from start up to, but not including, stop.a[1:3] has 3 - 1 = 2 items. A slice never raises an IndexError: a[2:10] just stops at the end.

a[start:stop:step]. The stop is left out.

Slicing · Going deeper · 1 of 2

More slices

a = [10, 20, 30, 40, 50]SliceGivesReads asa[-2:][40, 50]the last twoa[1:-1][20, 30, 40]all but the first and the lasta[1:4:2][20, 40]indexes 1 and 3a[4:1:-1][50, 40, 30]backwards from 4, stopping before 1a[2:10][30, 40, 50]a stop past the end is not an errora[:][10, 20, 30, 40, 50]everything: a copy of the listThe three parts are start, stop and step, and any of them may be left out.A negative start or stop counts from the end. A negative step walks backwards.

Negative counts from the end. a[:] is a copy.

Slicing · Going deeper · 2 of 2

A second name is not a copy

a = [1, 2, 3]b = ac = a[:]b.append(4)print(a, b, c)ab[1, 2, 3, 4]one list, two namesc[1, 2, 3]a separate copyb = a gives the same list a second name. a[:] makes a new list.So appending through b changes what a shows as well, and c is untouched. This prints[1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3]. Expect a question on it.

b = a: one list. a[:]: a new one.

Check yourself

a = [5, 6, 7, 8]print(a[1:3], a[-1])

What does this print?

Changing a list

A list can be changed in place

a = [10, 20, 30]102030a.append(40)10203040adds at the enda.insert(1, 15)1015203040puts 15 at index 1; the rest move updel a[0]15203040removes the item at index 0a[0] = 9999203040replaces the item at index 0A list can be changed in place.append() and insert() add, del removes, and an index on the left of = replaces. None ofthese makes a new list: the one list a refers to is altered, and its length changes with it.

append(), insert(), del, and a[i] = .

Changing a list · Going deeper

Searching a list

a = [10, 20, 30, 20]CodeGivesNotelen(a)4How many items20 in aTrueIs it there?a.index(20)1Where is the first one?a.index(99)ValueErrorindex() of a missing value is an errordel a[1:3]a is [10, 20]del also takes a slicea.append([1, 2])one new itemThe item added is itself a listCheck with in before you ask for index().append() always adds exactly one item, whatever you hand it.

in, index(), len().

Sorting

sorted() gives a new list. .sort() changes yours.

a = [3, 1, 2]b = sorted(a)c = a.sort()abc[3, 1, 2][3, 1, 2][1, 2, 3][1, 2, 3][1, 2, 3]Nonesorted() gives a new list. .sort() changes the one you have.sorted(a) leaves a alone and returns the sorted copy. a.sort() sorts a itself and returnsNone, so c = a.sort() loses nothing but gains nothing: c is None. Both take reverse=Truefor largest first. a.reverse() flips the order in place without sorting.

sorted(a) returns a copy. a.sort() returns None.

Sorting · Going deeper

Updating a list in a loop

By index: the list changesnums = [4, 7, 2]for i in range(len(nums)): nums[i] = nums[i] * 2print(nums)prints [8, 14, 4]By item: it does notnums = [4, 7, 2]for n in nums: n = n * 2print(nums)prints [4, 7, 2]To update the items of a list in a loop, go through the indexes.In the second loop n is only a name for each value in turn. Assigning to n moves that nameand leaves the list as it was. range(len(nums)) gives the indexes 0, 1, 2.

Use the indexes: range(len(nums)).

Check yourself

a = [1, 2, 3]b = ab[0] = 9print(a)

What does this print?

Lists of lists

A list of lists needs one index for each level

m = [[1, 2, 3], [4, 5, 6]]m[0]123m[1]456[0][1][2]m[1] is [4, 5, 6]the first index picks a rowm[1][0] is 4the second picks an item in that rowlen(m) is 2len(m[0]) is 3A list of lists needs one index for each level.m is a list with two items, and each item is a list of three. m[1] is a whole row. m[1][0]goes into that row. Read the indexes left to right: row, then column.

m[row][column]. m[1] is a whole row.

Lists of lists · Going deeper

Changing, looping, and a third level

Change one valuem = [[1, 2, 3], [4, 5, 6]]m[1][0] = 9print(m[1])prints [9, 5, 6]Visit every valuem = [[1, 2], [3, 4], [5, 6]]total = 0for row in m: for v in row: total += vprint(total)prints 21Three levels: a cubec = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]print(c[1][0][1])prints 6Two levels take a nested loop. Three levels take three indexes.c[1] is the second block, c[1][0] its first row, c[1][0][1] the second item of that row.Peel one index at a time and write down what is left.

Nested loop for two levels. c[1][0][1] for three.

Check yourself

m = [[1, 2], [3, 4]]print(m[1][0] + m[0][1])

What does this print?

Lesson complete

You finished “Lists”

Answer the questions along the way to see your score here.

Open in a new tab