Tuples
A tuple is like a list that cannot be changed. Use it for a fixed group of related values, such as coordinates. It has only two methods.
count(x) and index(x)
The only two tuple methods, same as for lists.
t = (1, 2, 2, 3)
print(t.count(2))
print(t.index(3))
Output:
2
3
Creating and unpacking
A single-item tuple needs a trailing comma. Unpacking pulls the values out.
single = (5,)
print(type(single), type((5)))
x, y = (3, 4)
print(x + y)
Output:
<class 'tuple'> <class 'int'>
7
namedtuple
A tuple whose items also have names: readable and still lightweight.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(2, 5)
print(p.x, p.y, p)
Output:
2 5 Point(x=2, y=5)
Sets
A set holds unique items with no order. It is very fast for "is this in here?" and for removing duplicates.
add(x), discard(x), remove(x)
discard does nothing if x is absent; remove raises an error.
s = {1, 2}
s.add(3)
s.add(3)
print(s)
s.discard(10)
s.remove(1)
print(s)
Output:
{1, 2, 3}
{2, 3}
Removing duplicates
Convert to a set and back. The order is not kept.
nums = [3, 1, 3, 2, 1]
print(sorted(set(nums)))
print(list(dict.fromkeys(nums)))
Output:
[1, 2, 3]
[3, 1, 2]
Set maths
| Operation | Operator | Method | Meaning |
|---|---|---|---|
| Union | a | b | a.union(b) | items in either |
| Intersection | a & b | a.intersection(b) | items in both |
| Difference | a - b | a.difference(b) | in a but not in b |
| Symmetric difference | a ^ b | a.symmetric_difference(b) | in one but not both |
maths = {"Ram", "Sita", "Hari"}
science = {"Sita", "Gita", "Hari"}
print(sorted(maths | science))
print(sorted(maths & science))
print(sorted(maths - science))
print(sorted(maths ^ science))
Output:
['Gita', 'Hari', 'Ram', 'Sita']
['Hari', 'Sita']
['Ram']
['Gita', 'Ram']
issubset, issuperset, isdisjoint
Compare two sets.
a = {1, 2}
b = {1, 2, 3}
print(a.issubset(b))
print(b.issuperset(a))
print(a.isdisjoint({7, 8}))
print(a <= b)
Output:
True
True
True
True
update(), pop(), clear()
Add many items, remove an arbitrary item, or empty the set.
s = {1}
s.update([2, 3, 3])
print(sorted(s))
s.clear()
print(s)
Output:
[1, 2, 3]
set()
frozenset
An unchangeable set. It can be used as a dictionary key or placed inside another set.
fs = frozenset([1, 2, 3])
print(2 in fs)
print({fs: "a group"}[frozenset([3, 2, 1])])
Output:
True
a group
{}makes an empty dictionary, not an empty set. Useset()for an empty set.
Try it yourself
- Find the letters two words have in common.
- Find which numbers appear in the list [1, 2, 3, 2, 4, 1] more than once, using a set to remember what you have seen.
- Check that every item of one list appears in another with
issubset.
Next lesson: dictionaries.

Comments
Loading comments…