Lists, tuples, sets, and dictionaries

3.15.2

Choose a collection by how you need to access, update, or deduplicate its contents.

On this page

Ordered sequences

Lists are mutable. Tuples have fixed slots, though an object inside a tuple can itself be mutable. A sequence slice includes its start and excludes its stop. A simple list slice makes a shallow copy.

items = ["Coffee", "Tea", "Cake", "Juice"]
print(items[1:3])
print(items[-2:])
Example output
['Tea', 'Cake']
['Cake', 'Juice']

Distinct values and keyed lookup

A set holds distinct hashable values and has no guaranteed iteration order. A dictionary stores values by hashable keys and preserves insertion order. get() supplies a default when a key is absent.

orders = ["Tea", "Coffee", "Tea"]
counts = {}
for item in orders:
    counts[item] = counts.get(item, 0) + 1
print(sorted(set(orders)))
print(counts)
Example output
['Coffee', 'Tea']
{'Tea': 2, 'Coffee': 1}

Build collections with comprehensions

A list comprehension adds the expression result for each matching input. Dict and set comprehensions use braces. A generator expression produces values as they are consumed.

quantities = [1, 4, 2, 5]
print([n * 2 for n in quantities if n > 2])
Example output
[8, 10]

Official references