BeginnerLesson 7 of 305 min read

Lists and tuples: collections of values

Store many values in lists, change, search and sort them, copy them safely, and use tuples for fixed groups.

In this lesson you will

  • Create, read and slice lists
  • Add, remove and sort items
  • Avoid the aliasing trap
  • Use tuples and unpacking

About 20 minutes

One variable, many values

Your shopping list is not five separate sheets of paper. It is one list with five lines. You can add to it, cross things off, count it and sort it. In Python that list is a list object, an ordered collection of values under one name. Lists drive almost everything: a feed of posts, a table of products, the results of a search.

Creating and reading lists

fruits = ["apple", "banana", "mango"]

print(fruits)
print(fruits[0])         # first
print(fruits[2])         # third
print(fruits[-1])        # last
print(len(fruits))       # how many

mixed = ["Sara", 28, True, 1.65]     # types can be mixed
empty = []
['apple', 'banana', 'mango']
apple
mango
mango
3

Slicing a list

nums = [10, 20, 30, 40, 50]
print(nums[1:4])      # [20, 30, 40]
print(nums[:2])       # first two
print(nums[-2:])      # last two
print(nums[::2])      # every second item
print(nums[::-1])     # reversed copy
[20, 30, 40]
[10, 20]
[40, 50]
[10, 30, 50]
[50, 40, 30, 20, 10]

Changing a list

Unlike strings, lists are mutable: you can change them in place.

todo = ["wash", "cook"]

todo.append("study")        # add to the end
todo.insert(0, "wake up")   # add at a position
print(todo)

todo[1] = "shower"          # replace an item
print(todo)

todo.remove("cook")         # remove by value
last = todo.pop()           # remove and return the last item
print(last, todo)

del todo[0]                 # delete by position
print(todo)
['wake up', 'wash', 'cook', 'study']
['wake up', 'shower', 'cook', 'study']
study ['wake up', 'shower']
['shower']
Method What it does
append(x) Add to the end
insert(i, x) Add at position i
extend(other) Add all items of another list
remove(x) Remove the first x
pop() / pop(i) Remove and return the last / i-th item
sort() Sort in place
reverse() Reverse in place
index(x) Position of x
count(x) How many times x appears
clear() Remove everything

Searching, counting, sorting

nums = [4, 9, 2, 9, 7]

print(9 in nums)             # True
print(nums.count(9))         # 2
print(nums.index(2))         # 2
print(max(nums), min(nums), sum(nums))

print(sorted(nums))                    # new sorted list
print(sorted(nums, reverse=True))      # biggest first
print(nums)                            # original untouched

nums.sort()                            # changes the list itself
print(nums)

names = ["mina", "Ali", "sara"]
print(sorted(names, key=str.lower))    # sort ignoring case
print(sorted(names, key=len))          # sort by length
True
2
2
9 2 31
[2, 4, 7, 9, 9]
[9, 9, 7, 4, 2]
[4, 9, 2, 9, 7]
[2, 4, 7, 9, 9]
['Ali', 'mina', 'sara']
['Ali', 'mina', 'sara']
Common mistake

Expecting sort() to return the sorted list. nums = nums.sort() sets nums to None, because sort() changes the list in place and returns nothing. Use sorted(nums) when you want a new list.

Joining and copying lists

a = [1, 2]
b = [3, 4]
print(a + b)           # join
print(a * 3)           # repeat

original = [1, 2, 3]
alias = original        # NOT a copy: both names point to the same list
alias.append(99)
print(original)         # changed too!

safe = original.copy()  # a real copy (or original[:] or list(original))
safe.append(100)
print(original, safe)
[1, 2, 3, 4]
[1, 2, 1, 2, 1, 2]
[1, 2, 3, 99]
[1, 2, 3, 99] [1, 2, 3, 99, 100]

Assigning one list to another variable does not copy it. Both names refer to the same list, so a change through one shows through the other. Make a real copy with .copy() when you need an independent list.

Lists of lists

grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]
print(grid[1][2])        # row 1, column 2 -> 6

for row in grid:
    print(row)

diagonal = [grid[i][i] for i in range(3)]
print(diagonal)
6
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[1, 5, 9]

Tuples: lists that cannot change

point = (3, 4)
print(point[0], point[1])

x, y = point             # unpacking
print(f"x={x}, y={y}")

single = (5,)            # note the comma for a one-item tuple

colours = ("red", "green")
# colours[0] = "blue"    # TypeError: tuples are immutable

def min_max(values):
    return min(values), max(values)   # returns a tuple

low, high = min_max([4, 8, 1])
print(low, high)
3 4
x=3, y=4
1 8

A tuple is like a list that cannot be changed after creation. Use tuples for fixed groups of values that belong together, such as a coordinate, a date or an RGB colour. Functions use tuples to return several values at once.

Unpacking and the star

first, *middle, last = [1, 2, 3, 4, 5]
print(first, middle, last)

names = ["Sara", "Ali"]
more = [*names, "Mina"]
print(more)
1 [2, 3, 4] 5
['Sara', 'Ali', 'Mina']

Processing lists: the map, filter, sum ideas

prices = [120, 45, 300, 80]

with_tax = [round(p * 1.17, 2) for p in prices]
print(with_tax)

expensive = [p for p in prices if p > 100]
print(expensive)

total = sum(prices)
average = total / len(prices)
print(f"Total {total}, average {average:.1f}")

cheapest = min(prices)
print("Cheapest at position", prices.index(cheapest))
[140.4, 52.65, 351.0, 93.6]
[120, 300]
Total 545, average 136.2
Cheapest at position 1
Practice

Given scores = [72, 91, 45, 68, 88], print the highest, the lowest, the average (one decimal) and how many scores are 70 or more.

Show one possible answer
scores = [72, 91, 45, 68, 88]
print("Highest:", max(scores))
print("Lowest:", min(scores))
print("Average:", round(sum(scores) / len(scores), 1))
print("70 or more:", len([s for s in scores if s >= 70]))
Highest: 91
Lowest: 45
Average: 72.8
70 or more: 3
Practice

Remove the duplicates from [3, 1, 3, 2, 1] while keeping the original order.

Hint: Build a new list and add an item only if it is not already there.

Show one possible answer
items = [3, 1, 3, 2, 1]
unique = []
for x in items:
    if x not in unique:
        unique.append(x)
print(unique)
[3, 1, 2]
Lists in, lists out

Most real programs read a list of things, process each one, and produce another list. Loops and comprehensions are the two tools; practise both until they feel automatic.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What index is the first item of a list?

  1. 1
  2. -1
  3. 0
  4. first

Python counts from zero.

Which method adds an item to the end?

  1. append
  2. pop
  3. remove
  4. sort

append adds at the end.

What does nums.sort() return?

  1. The sorted list
  2. A copy
  3. None; it sorts in place
  4. An error

sort() changes the list and returns None.

What is a tuple?

  1. An ordered collection that cannot be changed
  2. A kind of loop
  3. A dictionary
  4. A string method

Tuples are immutable.

Why does changing alias = original; alias.append(1) change original too?

  1. append is global
  2. Both names refer to the same list
  3. Lists are copied lazily
  4. It doesn’t

Assignment does not copy; use .copy().

Summary

  • Lists are ordered and mutable.
  • append, insert, remove, pop change a list.
  • sorted() returns a new list; sort() changes the old one.
  • Tuples are fixed lists, great for grouped values.

Next lesson

Next: dictionaries and sets, looking things up by name.

Questions

When should I use a tuple instead of a list?

When the group is fixed and belongs together, like coordinates. Lists suit collections that change.

How do I remove an item by position?

Use pop(i) or del lst[i]. remove(x) removes by value.

What is the difference between sorted and sort?

sorted() returns a new list and keeps the original. sort() changes the list in place and returns None.

Progress is saved in this browser.