← All lessons
Python intermediate · Lesson 3 of 11

Tuples and sets

A tuple is like a list that can't be changed once made. Write it with round brackets: point = (3, 4). Use one for a small group of values that belong together, like a coordinate or a date. Indexing and slicing work as with lists, but assigning to an item is an error.

point = (3, 4)
print(point[0])
print(len(point))
Prints
3
2

A value that can't be changed is called immutable. Strings and tuples are immutable; lists and dicts are mutable. Immutable values can be dictionary keys, which lists can't.

Unpacking splits a tuple (or list) into separate variables in one line. A function can return several values this way: it really returns one tuple, and the caller unpacks it. The same trick swaps two variables.

def min_max(nums):
    return min(nums), max(nums)

low, high = min_max([4, 9, 1, 7])
print(low, high)
a, b = 1, 2
a, b = b, a
print(a, b)
Prints
1 9
2 1

A set holds unique items with no order, in curly brackets: {1, 2, 3}. Adding something that's already there does nothing. Turning a list into a set is the quickest way to drop duplicates. (An empty set is set(), because {} makes an empty dict.)

nums = [3, 1, 3, 2, 1]
unique = set(nums)
print(len(unique))
print(sorted(unique))
Prints
3
[1, 2, 3]

Sets have no order, so they can't be indexed, and when you print one the order can change from run to run. Wrap it in sorted() when the order matters.

Sets are very fast at answering x in s, even with millions of items, because they don't have to look through every item the way a list does. They also do the maths of groups: | is union (in either), & intersection (in both) and - difference (in the first but not the second).

ana = {"chess", "piano", "golf"}
ben = {"golf", "chess", "darts"}
print(sorted(ana & ben))
print(sorted(ana - ben))
print(len(ana | ben))
Prints
['chess', 'golf']
['piano']
4

Practice

What does this print?

date = (2026, 11, 25)
year, month, day = date
print(month)
More info

Quick reference

(a, b)A tuple: like a list but immutable.
a, b = pairUnpacking into separate variables.
return x, yReturn several values (really one tuple).
{a, b} / set()A set of unique items / an empty set.
| & -Set union, intersection, difference.
mutable / immutableCan be changed in place (list, dict, set) / can't (str, tuple, int).

Related courses