Skip to content
Educora
Intermediate14 min7 / 42

Tuples and sets

Learn to use tuples for data that should not change and sets for collections without duplicates.

Check yourself
In this lesson you will learn
  • Create a tuple and unpack it
  • Explain the difference between a list, a tuple and a set
  • Remove duplicates with sets and use union, intersection and difference

Some data should never change: the days of the week, the geographic coordinates of Baku, the RGB code of a colour. At other times you only want unique values: say you want to know which cities visitors to a website come from, counting each city only once. Python has special types for these two jobs — the tuple and the set.

Tuples

Definition
Tuple

An ordered collection of values written in round brackets (). It is like a list, but it cannot be changed once created.

Python
baku = (40.41, 49.87)
print(baku)
print(baku[0])
print(len(baku))

days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
print(days[-1], days.index('Wed'))
▸ Expected output
(40.41, 49.87)
40.41
2
Sun 2

Indexes, slices, len(), in and the for loop all work with tuples too. But if you write days[0] = 'Monday', Python raises TypeError: 'tuple' object does not support item assignment. This is actually an advantage: no part of your program can change important data by mistake.

The handiest feature of tuples is unpacking: you can put the items into separate variables in one line. The same trick lets you swap two variables without a helper variable.

Python
lat, lon = (40.41, 49.87)
print('Latitude:', lat)
print('Longitude:', lon)

a = 5
b = 8
a, b = b, a
print(a, b)
▸ Expected output
Latitude: 40.41
Longitude: 49.87
8 5

Unpacking also works in loops. The enumerate() function gives each item together with its number as a (number, item) tuple — the easiest way to number a list. start=1 makes the counting begin at 1.

Python
students = ['Aysel', 'Murad', 'Leyla']
for number, name in enumerate(students, start=1):
    print(f'{number}. {name}')

print(list(enumerate('ab')))
▸ Expected output
1. Aysel
2. Murad
3. Leyla
[(0, 'a'), (1, 'b')]

Sets

Definition
Set

A collection of unique items written in curly braces {}. The items in a set have no order, so you cannot use indexes.

A set throws away duplicates automatically. If you pass a list to the set() function, only one of each value remains. Because a set has no order, we sort it with sorted() to print it neatly.

Python
print({3, 1, 2, 3, 1})

visitors = ['Baku', 'Ganja', 'Baku', 'Shaki', 'Ganja', 'Baku']
unique = set(visitors)
print(len(visitors), len(unique))
print(sorted(unique))

unique.add('Quba')
unique.add('Baku')
print(len(unique))
print('Shaki' in unique)
▸ Expected output
{1, 2, 3}
6 3
['Baku', 'Ganja', 'Shaki']
4
True

Notice that adding 'Baku' again changed nothing because it was already in the set — the count became 4, not 5. Checking with in is much faster for sets than for lists.

Example: unique words

How many words are there in the sentence “the sun and the moon and the stars”, and how many of them are unique?

Show solution
split() breaks the sentence into a list of 8 words.
set() drops the repeats, leaving the, sun, and, moon, stars.
Answer: 8 words, 5 of them unique.
Python
text = 'the sun and the moon and the stars'
words = text.split()
print(len(words), 'words,', len(set(words)), 'unique')
▸ Expected output
8 words, 5 unique

Set operations

The set operations you know from maths are written with a single symbol in Python. Suppose a school has a chess club and a robotics club. Which students go to both?

OperationSyntaxResult
Uniona | ball items in a or b
Intersectiona & bitems in both a and b
Differencea - bitems in a but not in b
Symmetric differencea ^ bitems in exactly one of them
Python
chess = {'Aysel', 'Murad', 'Elvin'}
robotics = {'Murad', 'Leyla', 'Elvin', 'Nigar'}

print(sorted(chess & robotics))
print(sorted(chess | robotics))
print(sorted(chess - robotics))
print(sorted(chess ^ robotics))
▸ Expected output
['Elvin', 'Murad']
['Aysel', 'Elvin', 'Leyla', 'Murad', 'Nigar']
['Aysel']
['Aysel', 'Leyla', 'Nigar']

Which one to choose?

FeatureListTupleSet
Syntax[1, 2](1, 2){1, 2}
Changeable?yesnoyes
Ordered?yesyesno
Duplicates allowed?yesyesno
Use it fora collection that changesfixed dataunique items, fast lookups
Exercise

Each item of results is a tuple of a name and a score, for example ('Aysel', 91). Using enumerate() and tuple unpacking, print the results numbered from 1, in the form 1. Aysel - 91.

Exercise · Python
results = [('Aysel', 91), ('Murad', 78), ('Leyla', 85)]
# print: 1. Aysel - 91, then 2. Murad - 78, ...
▸ Expected output
1. Aysel - 91
2. Murad - 78
3. Leyla - 85
Exercise

You have the lists of pupils who came to a club on Monday and on Tuesday (names can repeat). Using sets, print three lines: 1) how many different pupils came on Monday, 2) an alphabetical list of the pupils who came on both days, 3) how many different pupils came in total.

Exercise · Python
monday = ['Aysel', 'Murad', 'Leyla', 'Aysel', 'Elvin']
tuesday = ['Leyla', 'Nigar', 'Murad', 'Nigar']
# 1) number of different pupils on Monday
# 2) sorted list of pupils who came on both days
# 3) number of different pupils in total
▸ Expected output
4
['Leyla', 'Murad']
5

Key points

  • A tuple is an ordered collection in () that cannot be changed.
  • Unpacking assigns several variables in one line: lat, lon = point.
  • A set holds unique, unordered items in {}; set(list) removes duplicates.
  • | gives the union, & the intersection, - the difference and ^ the symmetric difference.
  • An empty set is made with set(); {} is an empty dictionary.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
What is the main difference between a tuple and a list?