Skip to content
Fullstack Launchpad

Python list, tuple, dict and set #1.2

Python has four types that hold several items: list, dict and set can change, a tuple cannot. Each fits a different job.

By Published Updated 4 min readPython for Engineers Switching Languages

list, tuple, dict, set

What does the code below print?

python
tags = ["python", "redis"]
tags.append("go")
print(tags[-1], len(tags))
# prints: go 3

prices = {"redis": 199_000}
prices["python"] = 249_000
print(prices.get("go"), "python" in prices)
# prints: None True

seen = set(["a", "b", "a"])
print(len(seen))
# prints: 2
  • len(x) returns the number of items in a list, dict, set or string.
  • prices.get("go") returns None because there is no key "go"; prices["go"] raises KeyError.

The whole lesson is about four types that hold several items: list, dict and set can change, a tuple cannot.

SectionExampleResult
listtags.append("go")tags[-1] is "go"
dictprices["python"] = 249_000prices.get("go") is None
setset(["a", "b", "a"])len(seen) is 2
tuplex, y = (3, 4)x + y is 7
listtupledictset
Create[1, 2](1, 2){"a": 1}{1, 2}
Reada[0], a[-1]t[0]d["a"], d.get("a")no access by position
Adda.append(3)cannotd["b"] = 2s.add(3)
Removea.pop(), a.remove(x)cannotdel d["a"], d.pop("a")s.discard(3)
x in ...slow, O(n)slow, O(n)fast, O(1), checks keysfast, O(1)
Use fora changing list of itemsa fixed record, returning several valueslookup by keyremoving duplicates, membership
  • d["x"] with no key "x" raises KeyError. d.get("x") returns None instead.
  • A dict keeps insertion order (since Python 3.7).
  • Adding or removing at the front of a list (insert(0, x), pop(0)) is O(n). For both ends use deque.
  • Checking membership many times on a list → switch to a set.

tuple: a fixed sequence

A tuple is an immutable sequence: once created, you cannot add, remove or reassign items. JS and Go have no such type, and the closest thing in Java is a record. Python uses tuples in many places where other languages use an array or a struct.

WriteMeaningResult
point = (3, 4)a two-item tuple(3, 4)
point = 3, 4the comma makes the tuple; brackets only help reading(3, 4)
(1,)a one-item tuple needs the comma(1,)
x, y = pointunpacking: split the tuple into namesx = 3, y = 4
return low, higha function returning several values returns one tuple(1, 9)
a, b = b, aswap two variablesno temporary variable
python
point = 3, 4
print(point)
# prints: (3, 4)
print(type((1)), type((1,)))
# prints: <class 'int'> <class 'tuple'>
x, y = point
print(x + y)
# prints: 7
point[0] = 10
# error: TypeError: 'tuple' object does not support item assignment

Returning several values and swapping two variables:

python
def min_max(nums):
    return min(nums), max(nums)


result = min_max([4, 1, 9])
print(result)
# prints: (1, 9)
low, high = min_max([4, 1, 9])
print(low, high)
# prints: 1 9

a, b = 1, 2
a, b = b, a
print(a, b)
# prints: 2 1

A tuple can be a dict key, a list cannot (see hashability in #1.4):

python
distance = {(0, 0): "origin", (3, 4): "5 from the origin"}
print(distance[(3, 4)])
# prints: 5 from the origin
print({[3, 4]: "error"})
# error: TypeError: unhashable type: 'list'

Trap: a tuple holding a list.

python
order = ("Orbit", [101, 102])
order[1].append(103)
print(order)
# prints: ('Orbit', [101, 102, 103])
print(hash(order))
# error: TypeError: unhashable type: 'list'

order[1] is still the same list; only its contents changed. Because one item is mutable, hash(order) fails.

Named tuples: NamedTuple. When each position has its own meaning, give it a name so you can read p.x instead of p[0]:

python
from typing import NamedTuple


class Point(NamedTuple):
    x: int
    y: int


p = Point(3, 4)
print(p.x, p[1])
# prints: 3 4
print(p)
# prints: Point(x=3, y=4)
  • class Point(NamedTuple): creates a tuple type with field names; x: int declares a field's name and type. Classes are covered in #3.1.
  • Point is still a tuple: you can read it by position, and you cannot reassign it.
PickWhen
tuplethe number of items and the meaning of each position are fixed: coordinates, a key–value pair, several return values
lista changing list of items of the same kind
NamedTuplea tuple where each position deserves a name

Key takeaways

  • For repeated lookups use a dict or set (O(1)), not a list (O(n)).
  • A tuple is immutable, made by the comma, (1,) for one item; use it for fixed records, several return values and dict keys.

Sources