KTU S1

Tuples and Sets

By the end you should be able to: Create and use tuples and sets, explain how each differs from a list, and choose the appropriate type for a given modelling problem.

Lists are not the only sequence type, and choosing the right one is a modelling decision — the point made in Module 1's "formulating a model".

Tuples — ordered, immutable

point = (3, 4)
rgb = (255, 128, 0)
single = (5,)           # the comma makes it a tuple
not_a_tuple = (5)       # this is just the integer 5

That trailing comma catches everyone once.

Tuples support everything lists do except changing:

point[0]        # 3       indexing works
point[0:1]      # (3,)    slicing works
len(point)      # 2
point[0] = 9    # TypeError — immutable

Why use one? Immutability is a guarantee, not a limitation. A tuple says "these values belong together and will not change" — coordinates, an RGB colour, a database row. It also means a tuple can be a dictionary key, which a list cannot:

locations = {(10, 20): "Depot", (15, 30): "Warehouse"}   # fine
locations = {[10, 20]: "Depot"}                          # TypeError

Unpacking

x, y = point                    # x = 3, y = 4
a, b = b, a                     # swap, no temp variable needed

That swap is the Module 2 three-line temp dance in one line. Python builds a tuple on the right and unpacks it on the left, so both original values are captured before either is overwritten.

Sets — unordered, unique

marks = {78, 92, 65, 92}
print(marks)            # {65, 78, 92}  — the duplicate is gone
empty = set()           # NOT {} — that is an empty dictionary

Three defining properties: no duplicates, no order, fast membership testing.

92 in marks             # True — very fast, whatever the size
marks.add(55)
marks.discard(65)       # no error if missing
marks.remove(65)        # KeyError if missing

Sets do not support indexing. marks[0] is a TypeError, because there is no first element.

Set operations

Genuinely useful, and they read like the mathematics:

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

a | b       # {1,2,3,4,5,6}   union
a & b       # {3, 4}          intersection
a - b       # {1, 2}          difference
a ^ b       # {1,2,5,6}       symmetric difference

For "which students took both subjects?" a set intersection is one character, where lists would need a nested loop.

Choosing between them

NeedType
Ordered, changeable collectionlist
Fixed group that must not change; a dict keytuple
Unique items; fast membership; set arithmeticset

Converting

list((1, 2, 3))         # [1, 2, 3]
tuple([1, 2, 3])        # (1, 2, 3)
set([1, 2, 2, 3])       # {1, 2, 3}
list(set([3,1,2,1]))    # [1, 2, 3]  — duplicates gone, ORDER NOT GUARANTEED

That last line is the standard "remove duplicates" idiom, but going through a set loses the original order. If order matters, sort afterwards or use a different approach.