Lists, dicts, sets and tuples

The four built-in collections, sorting, and list comprehensions.

Runs in Zerethon IDE · Python 3.12 Official Python documentation ↗
main.py
scores = [70, 95, 82]
scores.append(60)
print(sorted(scores), scores[0], scores[-1], len(scores))

scores.sort(reverse=True)
print(scores[:2])

ages = {"ada": 36, "alan": 41}
ages["grace"] = 85
print(ages.get("linus", "unknown"), "alan" in ages)
for name, age in sorted(ages.items()):
    print(name, age)

squares = [n * n for n in range(5) if n % 2 == 0]
print(squares, set([1, 1, 2]), (1, "a"))

people = [("bob", 25), ("amy", 31)]
print(sorted(people, key=lambda p: p[1], reverse=True))

Output

[60, 70, 82, 95] 70 60 4
[95, 82]
unknown True
ada 36
alan 41
grace 85
[0, 4, 16] {1, 2} (1, 'a')
[('amy', 31), ('bob', 25)]
  • sorted(x) returns a new list; x.sort() sorts in place and returns None.
  • Negative indexes count from the end; x[a:b] is a slice from a up to (not including) b.
  • d[key] raises KeyError for a missing key; d.get(key, default) does not.
  • Tuples cannot be changed after creation; sets keep one copy of each value, in no fixed order.