All coding lessonsLesson 6 of 10

Lists, Tuples, Sets and Dictionaries

Python's four essential collections

Lists — ordered and mutable

primes = [2, 3, 5, 7, 11]
print(primes[0])   # 2  (indexing starts at 0)
print(primes[-1])  # 11 (negative counts from the end)
primes.append(13)
primes.insert(0, 1)
primes.remove(1)
print(len(primes), sorted(primes, reverse=True))

Slicing

letters = ["a", "b", "c", "d", "e"]
print(letters[1:4])   # [b, c, d]  start included, stop excluded
print(letters[:2])    # [a, b]
print(letters[::2])   # [a, c, e]
print(letters[::-1])  # reversed copy

Tuples — ordered and immutable

point = (3, 4)
x, y = point          # unpacking
print(x, y)
# point[0] = 9 -> TypeError: tuples cannot be changed

Use a tuple when the number and meaning of the items is fixed (coordinates, RGB colours, a database row) and a list when the collection grows and shrinks.

Sets — unique and unordered

a = {1, 2, 3, 3, 2}
print(a)            # {1, 2, 3}
b = {3, 4, 5}
print(a & b)        # intersection {3}
print(a | b)        # union
print(a - b)        # difference
print(4 in b)       # membership test, very fast

Dictionaries — key to value mapping

capitals = {"Austria": "Vienna", "Italy": "Rome"}
print(capitals["Austria"])
capitals["France"] = "Paris"
print(capitals.get("Spain", "unknown"))

for country, city in capitals.items():
    print(country, "->", city)
print(list(capitals.keys()), list(capitals.values()))

Comprehensions

squares = [n ** 2 for n in range(10)]
evens = [n for n in range(20) if n % 2 == 0]
lengths = {w: len(w) for w in ["hi", "there"]}
unique_initials = {name[0] for name in ["Ada", "Alan", "Anna"]}

A comprehension is a compact loop that builds a collection. It is usually faster and clearer than an empty list plus append, as long as it stays on one readable line.

Ask Teacher Smith questions about this Python lessonOpens your AI tutor with a question about “Lists, Tuples, Sets and Dictionaries” →