Introduction
Tuples are immutable lists.
>>> my_tuple = (1,2,3)
>>> my_tuple
(1,2,3)
Parentheses are not what makes a tuple a tuple, it’s the commas.
>>> my_2nd_tuple = 1,2,3
>>> my_2nd_tuple
(1,2,3)
tuple( ) function
>>> my_3rd_tuple = tuple( [1,2,3] )
>>> my_3rd_tuple
(1,2,3)
Tuples are immutable!
>>> my_3rd_tuple[1]
2
>>> my_3rd_tuple[1] = 5
TypeError!
Packing & Unpacking
Simultaneous assignment is actually a tuple of values being assigned to another tuple.
>>> a, b = 1, 2
>>> a
1
>>> b
2
Unpacking
>>> c = (3,4)
>>> c
(3,4)
>>> d, e = c
>>> d
3
>>> e
4
Packing
>>> f = d, e
>>> f
(3, 4)
>> f == c
True
Swapping
>>> del a
>>> del b
>>> a = 1
>>> b = 2
>>> a, b = b, a
>>> a
1
>>> b
2
EXERCISE
The following is a function that takes a String and returns 4 versions of it in a tuple: uppercased, lowercased, capitalized and reversed.
def stringcases(my_string):
return my_string.upper(), my_string.lower(), my_string.title(), my_string[-1::-1]