Tuples and sets
A tuple is an ordered collection that can't be changed, written with round brackets: (52.5, 4.3). A set is an unordered collection of unique values, written with curly brackets: {"a", "b"}. Use tuples for fixed records and sets to remove duplicates or compare groups.
Tuples: fixed records
point = (3, 4)
brussels = ("Brussels", 50.85, 4.35)
print(point[0])
print(len(brussels))
city, lat, lon = brussels # unpacking
print(f"{city} is at {lat}, {lon}")3 3 Brussels is at 50.85, 4.35
Tuples are perfect when the values belong together and shouldn't change: coordinates, a date, a row from a database. Unpacking gives each value a name in one line.
point = (3, 4)
try:
point[0] = 10
except TypeError as err:
print("Error:", err)Error: 'tuple' object does not support item assignment
Functions can return tuples
numbers = [4, 9, 1, 7]
lowest, highest = min(numbers), max(numbers)
print(lowest, highest)
quotient, remainder = divmod(17, 5)
print(quotient, remainder)1 9 3 2
Sets: unique values
visits = ["anna", "ben", "anna", "cara", "ben"]
unique = set(visits)
print(len(unique))
print(sorted(unique))
unique.add("dev")
unique.discard("ben")
print("ben" in unique)3 ['anna', 'ben', 'cara'] False
Sets have no order and no positions, so unique[0] doesn't work. Checking x in a_set is very fast, even with millions of items.
Comparing groups
python_devs = {"anna", "ben", "cara"}
ai_devs = {"ben", "cara", "dev"}
print(sorted(python_devs & ai_devs)) # in both
print(sorted(python_devs | ai_devs)) # in either
print(sorted(python_devs - ai_devs)) # only in the first['ben', 'cara'] ['anna', 'ben', 'cara', 'dev'] ['anna']
Which one should I use?
| Type | Ordered | Changeable | Duplicates | Typical use |
|---|---|---|---|---|
list [] | Yes | Yes | Yes | A collection that grows or changes |
tuple () | Yes | No | Yes | A fixed record, e.g. coordinates |
set {} | No | Yes | No | Unique values, fast lookups |
Practice
Two teams worked on a project. team_a = ["ana", "raj", "li", "raj"] and team_b = ["li", "tom", "ana"]. Print, as sorted lists: everyone who worked on it (no duplicates), then the people in both teams.
['ana', 'li', 'raj', 'tom'] ['ana', 'li']