Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Python notes · Topic 8 of 22 · 4 min read

Python tuples and sets

Python tuples and sets notes: creating tuples, packing and unpacking, tuple vs list, sets for unique items, union, intersection and difference, with examples.

Tuples: like a list, but they cannot change

A tuple is an ordered collection written with round brackets. Once made, it cannot be changed (it is immutable).

point = (23.34, 85.31)        # latitude, longitude of Ranchi
days = ("Mon", "Tue", "Wed")
single = ("Asha",)            # a one-item tuple needs a comma
print(days[0], len(days))     # Mon 3

days[0] = "Sun"               # TypeError: 'tuple' object does not support item assignment

Indexing, slicing, len(), in, count() and index() all work. Methods that change a list (append, remove, sort) do not exist for tuples.

Packing and unpacking

Putting values together makes a tuple (packing); taking them out into variables is unpacking.

student = ("Asha", 15, "Ranchi")     # packing
name, age, city = student            # unpacking
print(name, city)                    # Asha Ranchi

first, *rest = (1, 2, 3, 4)          # first = 1, rest = [2, 3, 4]

A function can return several values as a tuple:

def min_max(nums):
    return min(nums), max(nums)

low, high = min_max([4, 9, 2])

When to use a tuple, when to use a list

Use a tuple whenUse a list when
the data should not change: coordinates, RGB colours, days of the weekitems will be added, removed or sorted
the position has a meaning: (name, age, city)every item is the same kind of thing: marks, names
you need a dictionary key (lists cannot be keys)you need methods like append and sort

Sets: unique items only, no order

A set keeps each value only once and has no fixed order.

visitors = {"asha", "ravi", "asha", "meena"}
print(visitors)            # {'ravi', 'asha', 'meena'}  (order may differ)
print(len(visitors))       # 3

empty = set()              # NOT {} -- that makes an empty dictionary
codes = set([1, 2, 2, 3])  # {1, 2, 3}

Because sets have no order, there is no visitors[0]. You can loop over a set and test membership, which is very fast:

visitors.add("kiran")
visitors.discard("ravi")   # no error if it is missing (remove() would raise KeyError)
print("asha" in visitors)  # True

The quickest way to remove duplicates from a list is list(set(items)), but the order is lost.

Set operations: the Venn diagram in Python

maths = {"Asha", "Ravi", "Meena"}
science = {"Ravi", "Meena", "Kiran"}

print(maths | science)    # union: in either club
print(maths & science)    # intersection: in both clubs -> {'Ravi', 'Meena'}
print(maths - science)    # difference: only maths -> {'Asha'}
print(maths ^ science)    # symmetric difference: in exactly one club
OperatorMethodMeaning
uniona.union(b)everything in a or b
intersectiona.intersection(b)only what is in both
differencea.difference(b)in a but not in b
symmetric differencea.symmetric_difference(b)in one but not both

Example: who has not submitted homework?

class_list = {"Asha", "Ravi", "Meena", "Kiran", "Zoya"}
submitted = {"Ravi", "Zoya"}
pending = class_list - submitted
print("Not submitted:", ", ".join(sorted(pending)))

Common mistakes

  • Writing ("Asha") for a one-item tuple: without the comma it is just a string.
  • Using {} for an empty set: that is an empty dictionary. Use set().
  • Expecting a set to keep the order you typed.
  • Trying to put a list inside a set: set items must be unchangeable (numbers, strings, tuples).

Key points

  • Tuples are ordered and unchangeable; use them for fixed groups of values.
  • Unpacking (a, b = pair) works for any tuple or list of the right length.
  • Sets hold unique values with no order; membership tests are fast.
  • |, &, - and ^ give union, intersection, difference and symmetric difference.

Practice questions

1. What is type(("x")) and what is type(("x",))?

str and tuple. The comma makes the tuple, not the brackets.

2. Count how many different words appear in a sentence.
words = input("Sentence: ").lower().split()
print(len(set(words)))
3. Two students' subjects are {"Maths", "Hindi", "IT"} and {"IT", "English", "Maths"}. Which subjects do they share?

a & b gives {"Maths", "IT"}.

4. Why can a tuple be a dictionary key but a list cannot?

Dictionary keys must never change. A tuple is immutable, so it is safe; a list can change, so Python refuses it.

5. Unpack ("Ranchi", 23.34, 85.31) into city, lat and lon and print them.
city, lat, lon = ("Ranchi", 23.34, 85.31)
print(city, lat, lon)