Tutorials › Python Tutorial › Python Tuples and Sets

Python Tuples and Sets

11 min read · Lesson 12 of 24

Lists are the all-rounders of Python, but two other collections are better for particular jobs. A tuple is a list that cannot change. A set is a bag of unique items with no order. This lesson covers both.

Tuples

A tuple is written with round brackets. Like a list it is ordered and allows duplicates, but once created it is immutable: you cannot add, remove or replace items.

Example PYTHON
coordinates = (-0.0917, 34.7680)   # Kisumu latitude, longitude
colours = ("black", "red", "green", "white")
print(coordinates)
print(colours[1])
print(len(colours))
Result
(-0.0917, 34.768)
red
4
Try it Yourself »

Indexing, slicing, len(), in and for loops all work on tuples exactly as on lists.

Why use a tuple?

  • It protects data that should not change, such as a date or GPS position.
  • It signals to other programmers that the values belong together as a fixed group.
  • Tuples can be used as dictionary keys; lists cannot (see Python Dictionaries).

A tuple with one item

A single value in brackets is not a tuple. You need a trailing comma.

Example PYTHON
not_a_tuple = ("Kenya")
real_tuple = ("Kenya",)
print(type(not_a_tuple).__name__)
print(type(real_tuple).__name__)
Result
str
tuple
Try it Yourself »

Unpacking

You can assign the items of a tuple to separate variables in one step. This is called unpacking.

Example PYTHON
athlete = ("Eliud Kipchoge", "Kenya", "Marathon")
name, country, event = athlete
print(name)
print(event)
Result
Eliud Kipchoge
Marathon
Try it Yourself »

An asterisk collects "the rest" into a list:

Example PYTHON
results = (1, 2, 3, 4, 5)
first, *middle, last = results
print(first, middle, last)
Result
1 [2, 3, 4] 5
Try it Yourself »

Changing a tuple (indirectly)

If you really must change a tuple, convert it to a list, change the list, and convert back.

Example PYTHON
days = ("Mon", "Tue", "Wed")
temp = list(days)
temp.append("Thu")
days = tuple(temp)
print(days)
Result
('Mon', 'Tue', 'Wed', 'Thu')
Try it Yourself »
Warning: Trying days[0] = "Sun" raises TypeError: 'tuple' object does not support item assignment.

Sets

A set is written with curly braces. Sets are:

  • Unordered – items have no position, so there is no indexing.
  • Unique – duplicates are removed automatically.
  • Changeable – you can add and remove items.

The fact that sets remove duplicates makes them perfect for questions like "which different towns did our customers come from?"

Example PYTHON
customer_towns = ["Kisumu", "Nakuru", "Kisumu", "Eldoret", "Nakuru"]
unique_towns = set(customer_towns)
print(len(unique_towns))
print(sorted(unique_towns))
Result
3
['Eldoret', 'Kisumu', 'Nakuru']
Try it Yourself »
Note: When you print a set directly, the order of items may look random and can differ between runs. Use sorted() when you need a predictable order.

Adding and removing

Example PYTHON
tags = {"python", "beginner"}
tags.add("kenya")
tags.add("python")          # already there, nothing happens
tags.discard("beginner")
print(sorted(tags))
print("kenya" in tags)
Result
['kenya', 'python']
True
Try it Yourself »

remove(x) also deletes an item, but raises an error if it is missing. discard(x) stays silent.

Set operations

Sets support the classic maths operations. Suppose two clubs at a school:

Example PYTHON
football = {"Otieno", "Mwangi", "Kibet", "Hassan"}
drama = {"Kibet", "Wanjiru", "Hassan", "Achieng"}

print(sorted(football | drama))   # union: in either club
print(sorted(football & drama))   # intersection: in both
print(sorted(football - drama))   # difference: football only
print(sorted(football ^ drama))   # in exactly one club
Result
['Achieng', 'Hassan', 'Kibet', 'Mwangi', 'Otieno', 'Wanjiru']
['Hassan', 'Kibet']
['Mwangi', 'Otieno']
['Achieng', 'Mwangi', 'Otieno', 'Wanjiru']
Try it Yourself »

The same operations are available as methods: union(), intersection(), difference() and symmetric_difference().

An empty set

{} creates an empty dictionary, not a set. Use set() instead.

Example PYTHON
print(type({}).__name__)
print(type(set()).__name__)
Result
dict
set
Try it Yourself »

Choosing a collection

TypeBracketsOrderedChangeableDuplicates
list[ ]YesYesYes
tuple( )YesNoYes
set{ }NoYesNo
dict{key: value}YesYesNo duplicate keys

Exercises

Exercise

Create a tuple with a single item.

one = ("Kenya")
Exercise

Add "Nyeri" to the set.

towns = {"Meru", "Embu"}
towns.("Nyeri")

Next: Python Dictionaries.

Sign in or create a free account to track progress, earn XP, badges and a certificate.