Lists

Creating lists, indexes, adding and removing elements.

A list keeps several values in order. It is written in square brackets, and the elements can be anything, even other lists:

scores = [70, 85, 92]
print(scores[0], scores[-1], len(scores))   # 70 92 3

Indexes and slices work the same as with strings. The main difference is that a list is mutable: scores[0] = 75 changes an element in place.

The main operations:

  • append(x) adds an element at the end, insert(i, x) at position i;
  • pop() removes and returns the last element, pop(i) the element at index i;
  • remove(x) removes the first occurrence of a value and raises ValueError if there is none;
  • x in items checks for presence, items.index(x) finds the position;
  • extend(other) or += adds all the elements of another list.

append adds one element, even if that element is a list: a.append([1, 2]) puts a nested list inside. To add the elements one by one you need extend.

An important property: assignment does not copy a list, it gives a second name to the same object.

a = [1, 2]
b = a
b.append(3)
print(a)   # [1, 2, 3]

The change made through b is visible through a, because it is the same list. A copy is made explicitly: b = a.copy() or b = a[:]. The same trap appears when a list is passed to a function and the function changes it.

An empty list is [], a list from a range is list(range(5)), a list of the characters of a string is list("abc").

Practice

  1. Two names

    What does the program print?

    a = [1, 2]
    b = a
    b.append(3)
    print(a)
    
  2. What pop does

    What does items.pop() with no arguments do?

    • Removes the last element and returns it
    • Removes the first element and returns nothing
    • Returns the last element without removing it
    • Clears the whole list
  3. The last three

    Write a function last_three(items) that returns a new list of the last three elements. If there are fewer than three elements, return them all.