Tuples
We'll cover the following...
A tuple is an immutable list. A tuple can not be changed in any way once it is created.
a_tuple = ("a", "b", "mpilgrim", "z", "example") #①print (a_tuple)#('a', 'b', 'mpilgrim', 'z', 'example')print (a_tuple[0] ) #②#aprint (a_tuple[-1]) #③#exampleprint (a_tuple[1:3] ) #④#('b', 'mpilgrim')
① A tuple is defined in the same way as a list, except that the whole set of elements is enclosed in parentheses instead of square brackets.
② The elements of a tuple have a defined order, just like a list. Tuple indices are zero-based, just like a list, so the first element of a non-empty tuple is always a_tuple[0]
.
③ Negative indices count from the end of the tuple, just like a list.
④ Slicing works too, just like a list. When you slice a list, you get a new list; when you slice a tuple, you get a new tuple.
The major difference between tuples and lists is that tuples can not be changed. In technical terms, tuples are immutable. In practical terms, they have no methods that would allow you to change them. Lists have methods like append()
, extend()
, insert()
, remove()
, and ...