This session covers three collection types → Tuples, Sets, and Dictionaries. The results below are the real ones. Errors that were left in on purpose are kept as learning moments.

Tuples

A tuple is like a list, but immutable → once created, you cannot change it in any way. Think of it as a read-only list.

Characteristics:

Creating Tuples

t1 = ()                      # empty
print(t1)                    # ()

t2 = ('hello',)              # a single item NEEDS a trailing comma
print(t2)                    # ('hello',)
print(type(t2))              # <class 'tuple'>

t3 = (1,2,3,4)               # homogeneous
print(t3)                    # (1, 2, 3, 4)

t4 = (1,2.5,True,[1,2,3])    # heterogeneous
print(t4)                    # (1, 2.5, True, [1, 2, 3])

t5 = (1,2,3,(4,5))           # a tuple inside a tuple
print(t5)                    # (1, 2, 3, (4, 5))

t6 = tuple('hello')          # type conversion
print(t6)                    # ('h', 'e', 'l', 'l', 'o')

Careful: ('hello') without the comma is just a string in brackets. The comma is what makes it a tuple.

Accessing items

t3 = (1,2,3,4)
print(t3[0])    # 1    (indexing)
print(t3[-1])   # 4    (negative indexing)

t5 = (1,2,3,(4,5))
t5[-1][0]       # 4    (dig into the nested tuple)

t = (1,2,3,4,5)
t[-1:-4:-1]     # (5, 4, 3)   (slicing works, returns a new tuple)

Editing items

Tuples are immutable, so this fails:

t3 = (1,2,3,4)
t3[0] = 100
# TypeError: 'tuple' object does not support item assignment

Adding items

Also not possible. A tuple has no append or extend, so you cannot add to it after creation.

Deleting items

You cannot delete a single item:

t5 = (1,2,3,(4,5))
del t5[-1]
# TypeError: 'tuple' object doesn't support item deletion