Skip to content

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 use sum, min, max, and sorted.

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:

  1. The list starts with two items. append("cherry") adds a third item at the end.
  2. insert(0, "mango") places "mango" at index 0, so the other items shift one place to the right.
  3. len(fruits) counts four items. fruits[1] reads index 1, which is "apple".
  4. pop() removes the last item, "cherry", and gives it back. The variable last stores it.
  5. sum, min, and max read the list scores and return 248, 72, and 91.
  6. sorted(scores) returns a new list in ascending order. The original scores is unchanged, as the last print shows.

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.

colors = ["red", "green"]
colors.append("blue")
assert colors == ["red", "green", "blue"]
assert len(colors) == 3
assert colors[-1] == "blue"
colors[0] = "pink"
assert colors[0] == "pink"
numbers = [5, 2, 9, 2]
assert numbers.count(2) == 2
numbers.remove(2)
assert numbers == [5, 9, 2]
assert sorted(numbers) == [2, 5, 9]
assert numbers == [5, 9, 2]
assert numbers.sort() is None
assert numbers == [2, 5, 9]
assert numbers.pop() == 9
assert numbers == [2, 5]
a = [1, 2]
b = a
b.append(3)
assert a == [1, 2, 3]

c = a.copy()
c.append(4)
assert a == [1, 2, 3]
assert c == [1, 2, 3, 4]

total = 0
for value in a:
    total = total + value
assert total == 6
assert 2 in a

Common mistakes

  1. Reading past the last index. The code letters = ["a", "b"] followed by print(letters[2]) gives:

    IndexError: list index out of range
    

    A list of length 2 has indexes 0 and 1. The last index is len(letters) - 1.

  2. Assigning the result of sort(). The code nums = [3, 1, 2] followed by nums = nums.sort() and print(nums[0]) gives:

    TypeError: 'NoneType' object is not subscriptable
    

    The method sort() returns None. Call nums.sort() on its own line, or write nums = sorted(nums).

  3. Removing a value that is not there. The code nums = [1, 2] followed by nums.remove(5) gives:

    ValueError: list.remove(x): x not in list
    

    Check first with if 5 in nums:.

  4. Joining a list and a number with +. The code print([1, 2] + 3) gives:

    TypeError: can only concatenate list (not "int") to list
    

    To add one item, use append(3). To join two lists, use [1, 2] + [3].

  5. Passing two values to append. The code nums = [1] followed by nums.append(2, 3) gives:

    TypeError: list.append() takes exactly one argument (2 given)
    

    Call append with one value. To add several items, use extend or several append lines.

Practice

  1. Create cities = ["Oslo", "Rome"]. Append "Lima" and assert that len(cities) is 3.
  2. Create nums = [4, 8, 15]. Assert that nums[-1] is 15 and that sum(nums) is 27.
  3. Start with squares = []. Use a for loop over range(1, 6) and append n * n for each n. Assert that squares equals [1, 4, 9, 16, 25].
  4. Create words = ["pear", "apple", "fig"]. Assign ordered = sorted(words). Assert that ordered equals ["apple", "fig", "pear"] and that words still equals ["pear", "apple", "fig"].
  5. Stretch: create nums = [3, 8, 1, 8, 5]. Use a while loop with while 8 in nums: and remove(8) to delete every 8. Assert that nums equals [3, 1, 5].
Solution
  1. python cities = ["Oslo", "Rome"] cities.append("Lima") assert len(cities) == 3

  2. python nums = [4, 8, 15] assert nums[-1] == 15 assert sum(nums) == 27

  3. python squares = [] for n in range(1, 6): squares.append(n * n) assert squares == [1, 4, 9, 16, 25]

  4. python words = ["pear", "apple", "fig"] ordered = sorted(words) assert ordered == ["apple", "fig", "pear"] assert words == ["pear", "apple", "fig"]

  5. 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, and pop to change it.
  • Methods such as sort() change the list in place and return None. sorted(...) returns a new list.
  • Assigning one list to another name does not copy it. Use .copy() for an independent list.

Sources