</>CodexBash
Python
PythonBeginner12 min

Lists and tuples

Creating, reading and changing lists, adding and removing items, sorting, list comprehensions, two-dimensional lists and the classic trap, and when to use a tuple.

Adding and removing in a liststep 1/5
72
88
95
size = 3
A list of three scores, at positions 0, 1 and 2.

A list holds many values in order, under one name. It is the workhorse of Python: most programs are, at heart, something done to a list.

Making a list#

scores = [72, 88, 95, 60]
names = ["Asha", "Ravi"]
mixed = [1, "two", 3.0, True]     # allowed, though rarely a good idea
empty = []

Reading items#

Lists index and slice exactly like strings:

scores[0]       # 72
scores[-1]      # 60
scores[1:3]     # [88, 95]
len(scores)     # 4
88 in scores    # True

Changing items#

Unlike strings, lists can be changed in place:

scores[0] = 75          # [75, 88, 95, 60]

Adding and removing#

scores.append(80)       # add to the end:        [75, 88, 95, 60, 80]
scores.insert(0, 50)    # add at position 0:     [50, 75, 88, 95, 60, 80]
scores.pop()            # remove and return the last: 80
scores.pop(0)           # remove and return position 0: 50
scores.remove(95)       # remove the first 95
scores.extend([1, 2])   # add several to the end

Adding or removing at the end is fast. At the front every other item has to shift along, which is slow for big lists. If you need both ends, collections.deque is built for it.

Looping#

for score in scores:
    print(score)

for i, score in enumerate(scores):
    print(i, score)

Sorting#

nums = [5, 2, 9, 1]
nums.sort()                  # changes nums: [1, 2, 5, 9]
nums.sort(reverse=True)      # [9, 5, 2, 1]

ordered = sorted([5, 2, 9])  # a new sorted list; the original is untouched

words = ["banana", "kiwi", "apple"]
words.sort(key=len)          # by length: ['kiwi', 'apple', 'banana']

sort changes the list and returns None, so nums = nums.sort() loses your list. Use sorted when you want the result as a value.

List comprehensions#

A compact way to build one list from another:

squares = [x * x for x in range(5)]            # [0, 1, 4, 9, 16]
evens = [x for x in nums if x % 2 == 0]
lengths = [len(w) for w in words]

Read it as "x times x, for each x in range 5". It does the same as a loop with append, in one line. Keep them short; when it needs more than one condition, a plain loop reads better.

Useful built-ins#

sum([1, 2, 3])      # 6
max([4, 9, 2])      # 9
min([4, 9, 2])      # 2
list("abc")         # ['a', 'b', 'c']
list(range(3))      # [0, 1, 2]

Two-dimensional lists#

A list of lists makes a grid; grid[row][col] reads one cell:

grid = [[0] * 3 for _ in range(2)]   # 2 rows, 3 columns of zeros
grid[0][1] = 5
print(grid)                          # [[0, 5, 0], [0, 0, 0]]

The classic trap: [[0] * 3] * 2 looks the same but makes two references to the same row, so changing one row changes both. Always build rows with a comprehension as above.

Copying#

b = a does not copy a list; both names refer to the same one. To copy:

b = a.copy()     # or a[:] or list(a)

Tuples#

A tuple is like a list that cannot change, written with round brackets:

point = (3, 4)
x, y = point          # unpacking

Use a tuple for a fixed group of values that belong together, such as a coordinate or a function returning two results. Use a list for a collection that grows, shrinks or changes.

Key points#

  • Lists are ordered and changeable; index and slice like strings.
  • append and pop at the end are fast; the front is slow.
  • sort() changes the list; sorted() returns a new one.
  • Comprehensions build lists in one line.
  • Build grids with a comprehension, never [[0] * n] * m.
  • b = a shares; a.copy() copies.

That completes the basics. From here, try the practice problems below, then the Learn track, which uses these tools to build real algorithms.

Practise it

The same idea, in the order it is worth meeting it.

  1. Not startedRunning sumEasy
  2. Not startedMove the zeroes to the endEasy
  3. Not startedContains duplicateEasy
Create a free account to track your progress