Tuples: Lists That Don't Change

What is a tuple?

A tuple is like a list, but once it's made it can't be changed. Tuples use round brackets ( ).

point = (3, 5)
rgb_red = (255, 0, 0)
print(point[0])
print(len(rgb_red))

Output

3
3

Use a tuple for values that belong together and shouldn't change, like coordinates or a date.

birthday = (2004, 8, 15)
birthday[0] = 2005

Output (Python stops with an error)

TypeError: 'tuple' object does not support item assignment

Trying to change it gives a TypeError. That protection is the whole point of a tuple.

Unpacking

You can take a tuple apart into separate variables in one line:

person = ("Asha", 21, "Pune")
name, age, city = person
print(name)
print(city)

Output

Asha
Pune

You've already seen this trick: a, b = b, a swaps two variables using a tuple.

HOME LEARN COMMUNITY DASHBOARD