Python Functions and Methods: A Topic-by-Topic Reference · Lesson 7 of 12

Lesson 7: Tuples and Sets

Tuples for fixed data, sets for unique items: add, discard, union, intersection, difference, subsets and frozenset.

Lesson 7: Tuples and Sets

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

OperationOperatorMethodMeaning
Uniona | ba.union(b)items in either
Intersectiona & ba.intersection(b)items in both
Differencea - ba.difference(b)in a but not in b
Symmetric differencea ^ ba.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. Use set() for an empty set.

Try it yourself

  1. Find the letters two words have in common.
  2. 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.
  3. Check that every item of one list appears in another with issubset.

Next lesson: dictionaries.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 7: Tuples and Sets | MeroSir