Lists¶
~20 min ยท prerequisite: Variables and types
What you will be able to do¶
- Create a list with square brackets, read items by index, and find how many items it holds.
- Change a list with
append,insert,remove,pop, and item assignment. - Loop over a list with
for, and usesum,min,max, andsorted.
The idea¶
A list is an ordered collection of values written in square brackets and separated by commas, such as [3, 1, 4]. The items may have different types, as in ["Ada", 36, True], but most lists hold values of one kind. Like a string, a list is a sequence, so each item has an index that starts at 0. Unlike a string, a list is mutable, which means you can change it in place.
Several methods change a list. The method append(x) adds x to the end. The method insert(i, x) adds x at position i, and the items after it move one place to the right. The method remove(x) deletes the first item equal to x. The method pop() removes the last item and returns it, and pop(i) removes the item at index i. You can also replace an item with an assignment such as nums[0] = 10.
The method sort() sorts the list in place and returns None, which means "no value". If you write nums = nums.sort(), you lose the list. The built-in function sorted(nums) returns a new sorted list and leaves nums alone. The functions len, sum, min, and max read a list without changing it.
Assignment does not copy a list. After b = a, both names refer to the same list, so a change through b is also visible through a. To make an independent copy, call a.copy().
Lists also work with in, which tests whether a value appears in the list, and with for, which visits each item in order.
Worked example¶
fruits = ["apple", "banana"]
fruits.append("cherry")
fruits.insert(0, "mango")
print(fruits)
print(len(fruits))
print(fruits[1])
last = fruits.pop()
print("removed", last)
print(fruits)
scores = [72, 91, 85]
print(sum(scores), min(scores), max(scores))
print(sorted(scores))
print(scores)
Line by line, this is what Python does:
- The list starts with two items.
append("cherry")adds a third item at the end. insert(0, "mango")places"mango"at index 0, so the other items shift one place to the right.len(fruits)counts four items.fruits[1]reads index 1, which is"apple".pop()removes the last item,"cherry", and gives it back. The variablelaststores it.sum,min, andmaxread the listscoresand return248,72, and91.sorted(scores)returns a new list in ascending order. The originalscoresis unchanged, as the lastprintshows.
The output is:
['mango', 'apple', 'banana', 'cherry']
4
apple
removed cherry
['mango', 'apple', 'banana']
248 72 91
[72, 85, 91]
[72, 91, 85]
Try it¶
The first block checks reading and changing items. The second block checks remove, sort, and sorted. The third block checks that two names can refer to one list.
Common mistakes¶
-
Reading past the last index. The code
letters = ["a", "b"]followed byprint(letters[2])gives:A list of length 2 has indexes 0 and 1. The last index is
len(letters) - 1. -
Assigning the result of
sort(). The codenums = [3, 1, 2]followed bynums = nums.sort()andprint(nums[0])gives:The method
sort()returnsNone. Callnums.sort()on its own line, or writenums = sorted(nums). -
Removing a value that is not there. The code
nums = [1, 2]followed bynums.remove(5)gives:Check first with
if 5 in nums:. -
Joining a list and a number with
+. The codeprint([1, 2] + 3)gives:To add one item, use
append(3). To join two lists, use[1, 2] + [3]. -
Passing two values to
append. The codenums = [1]followed bynums.append(2, 3)gives:Call
appendwith one value. To add several items, useextendor severalappendlines.
Practice¶
- Create
cities = ["Oslo", "Rome"]. Append"Lima"and assert thatlen(cities)is 3. - Create
nums = [4, 8, 15]. Assert thatnums[-1]is 15 and thatsum(nums)is 27. - Start with
squares = []. Use aforloop overrange(1, 6)and appendn * nfor eachn. Assert thatsquaresequals[1, 4, 9, 16, 25]. - Create
words = ["pear", "apple", "fig"]. Assignordered = sorted(words). Assert thatorderedequals["apple", "fig", "pear"]and thatwordsstill equals["pear", "apple", "fig"]. - Stretch: create
nums = [3, 8, 1, 8, 5]. Use awhileloop withwhile 8 in nums:andremove(8)to delete every 8. Assert thatnumsequals[3, 1, 5].
Solution
-
python cities = ["Oslo", "Rome"] cities.append("Lima") assert len(cities) == 3 -
python nums = [4, 8, 15] assert nums[-1] == 15 assert sum(nums) == 27 -
python squares = [] for n in range(1, 6): squares.append(n * n) assert squares == [1, 4, 9, 16, 25] -
python words = ["pear", "apple", "fig"] ordered = sorted(words) assert ordered == ["apple", "fig", "pear"] assert words == ["pear", "apple", "fig"] -
python nums = [3, 8, 1, 8, 5] while 8 in nums: nums.remove(8) assert nums == [3, 1, 5]
Recap¶
- A list is an ordered, mutable sequence written in square brackets. Use
append,insert,remove, andpopto change it. - Methods such as
sort()change the list in place and returnNone.sorted(...)returns a new list. - Assigning one list to another name does not copy it. Use
.copy()for an independent list.