Tuples & Sets
Lists aren't the only way to group values in Python. A tuple is an ordered collection like a list, but locked once created; a set drops the order entirely and instead guarantees every value in it is unique.
Tuples: ordered, but unchangeable
Parentheses (or often just commas) create a tuple. It supports indexing and slicing exactly like a list, but has no .append(), .remove(), or item assignment:
point = (3, 7) print(point[0]) print(point[1]) point[0] = 10
3 7 Traceback (most recent call last): ... TypeError: 'tuple' object does not support item assignment
Reading point[0] and point[1] works exactly like a list. But a tuple is immutable — once it's created, its contents can never change in place — so the assignment on the last line crashes.
Why use a tuple instead of a list
Immutability is the point, not a limitation. A tuple is the natural choice for a fixed grouping of values that should never accidentally get edited, like a coordinate pair or a database row, and functions can return multiple values at once by packing them into one:
def min_and_max(numbers):
return min(numbers), max(numbers)
low, high = min_and_max([4, 9, 1, 7])
print(low, high)
1 9
return min(numbers), max(numbers) packs both values into a two-item tuple automatically, and low, high = ... unpacks it straight into two separate variables in one line.
Sets: only unique values, no order
Curly braces without : pairs create a set. Adding a duplicate has no effect, and sets support the same mathematical operations you'd expect — union, intersection, difference:
tags = {"python", "code", "python", "tutorial", "code"}
print(tags)
print(len(tags))
{'python', 'code', 'tutorial'}
3students_python = {"Amir", "Beatriz", "Chen"}
students_java = {"Chen", "Dana"}
print(students_python & students_java)
print(students_python | students_java)
print(students_python - students_java)
{'Chen'}
{'Amir', 'Beatriz', 'Chen', 'Dana'}
{'Amir', 'Beatriz'}& is the intersection (students in both classes), | is the union (everyone, no duplicates), and - is the difference (students in the Python class but not the Java one).
in is dramatically faster on a set than on a list once you're dealing with a lot of data — a list has to check items one by one, while a set can jump almost straight to the answer. If you find yourself writing if x in some_big_list: purely to check for existence rather than to preserve order, a set is usually the better container. Also remember that since a set has no order, you can't index into one with tags[0].