Python Programming · Lesson 8 of 15 · Updated ·
Tuples and Sets in Python — When to Use Each
Python has four built-in collections. You know lists; this lesson covers tuples and sets, and compares all four.
Part A — Tuples
A tuple is like a list that cannot change (immutable). Use round brackets.
point = (3, 4)
print(point[0], len(point))
rgb = 255, 128, 0 # brackets are optional
print(type(rgb))
single = (5,) # one item needs a comma
print(type(single), type((5)))
3 2
<class 'tuple'>
<class 'tuple'> <class 'int'>
Why use tuples?
- To store values that shouldn't change (coordinates, date parts, RGB colours).
- Tuples can be dictionary keys and set items; lists can't.
- Functions return several values as a tuple.
Unpacking
def min_max(nums):
return min(nums), max(nums)
low, high = min_max([7, 2, 9, 4])
print(low, high)
first, *rest = [10, 20, 30, 40]
print(first, rest)
2 9
10 [20, 30, 40]
Part B — Sets
A set keeps only unique items and has no order. It's very fast at checking x in s.
nums = [3, 1, 3, 2, 1, 3]
unique = set(nums)
print(len(unique), sorted(unique))
skills = {"python", "sql"}
skills.add("git")
skills.add("python") # already there — no duplicate
skills.discard("java") # no error if missing
print(sorted(skills))
3 [1, 2, 3]
['git', 'python', 'sql']
An empty set is
set(), not{}— that's an empty dictionary.
Set operations (like Venn diagrams)
python_students = {"Asha", "Ravi", "Neha"}
java_students = {"Ravi", "Kabir", "Neha"}
print(sorted(python_students | java_students)) # union: in either
print(sorted(python_students & java_students)) # intersection: in both
print(sorted(python_students - java_students)) # difference: only Python
print(sorted(python_students ^ java_students)) # in exactly one
['Asha', 'Kabir', 'Neha', 'Ravi']
['Neha', 'Ravi']
['Asha']
['Asha', 'Kabir']
Which one should I use?
| Need | Use |
|---|---|
| An ordered collection that changes | list |
| Fixed values, or a dict key | tuple |
| Unique items / fast "is it in there?" | set |
| Look up a value by a name | dict (next lesson) |
Common mistakes
(5)is just the number 5; a one-item tuple needs a comma:(5,).- Using
{}to make an empty set (it makes a dict). - Expecting a set to keep insertion order or allow indexing (
s[0]is an error).
Quick recap
- Tuple: ordered, immutable,
( ); great for fixed data and returning many values. - Set: unique, unordered,
{ };add,discard,|,&,-,^. set()for an empty set.