Tuples are another object type in Python. Tuples are like lists, except that tuples are immutable. Here is how a tuple is defined:
t = (1, 2, 3, 4)
You can access elements of tuples just like you access elements of lists:
t[1]
t[1:]
Tuples can contain objects that are not tuples inside them:
t = ([1, 2], 3)
t[0]
Tuples are immutable. That means we cannot modify their contents:
t[0] = 5
That doesn't mean that we can't modify the contents of the contents of tuples:
t
t[0][1] = 5
t
We often want to unpack tuples. That means that for a tuple t, we want to put t[0] in one variable, t[1] in another variable, and so on. Here is how this works:
t = ("a", "b", "c")
i, j, k = t #same as i = t[0], j = t[1], k = t[2]
print(i, j, k)
Note that we have to provide the right number of variables to unpack into:
a, b = t
We've actually already seen tuple unpacking, several times. Here is how we did variable swapping:
a = 42
b = 43
a, b = b, a #create a new tuple (b, a), and then upack it into the variables a, b
We also saw tuple unpacking when "returning multiple objects from a function"
def f():
return 42, 43
if __name__ == '__main__':
a, b = f() #a == 42 and b == 43
Here, the function f() actually returns the tuple (42, 43), which then gets unpacked into the variables a and b. We alternatively could use f() as follows:
t = f()
a = t[0]
b = t[1]