Python Tuple
Python tuple is an immutable list which cannot be modified once it is created. In order to define a tuple you assign a sequence of values to a variable. Different from a list, the set of tuple's elements is enclosed in parentheses.
tuple = ("x","y","z")
print(tuple[0]) # x
print(tuple[-1]) # z
print(tuple[0:3]) # ('x', 'y', 'z')
As you see in the code snippet above:
- Like a list, tuple's indices are zero-base therefore the first element of a tuple is tuple[0]
- Negative indices starts from the end of the tuple.
- Slicing like a list is applied to a tuple to so you get a new tuple when you slice a tuple.
Tuple is similar to a list except it has no method so you cannot add/remove elements from a tuple. Tuple is designed to be very useful in the following cases:
- Because tuple is immutable so a tuple is faster than a list. If you intend to use a readonly list, you can use tuple instead.
- Tuples can be used as dictionary keys because it is immutable. List cannot be used as a dictionary key because list is mutable.
- Tuples are used to format string.
Converting tuples into lists
Tuple can be converted into list and vice versa. To convert a tuple into a list you use function list as follows:
tuple = ("a","b","c")
l = list(tuple)# convert tuple into list
print(l) # ['a', 'b', 'c']
Lists also can be converted into tuples. To convert a list into a tuple you use the built-in function tuple as follows:
list=['1','2','3']
tuple = tuple(list) # convert a list into a tuple
print(tuple) # ('1', '2', '3')
Defining a tuple with one element
It is exception for tuple that when you define a tuple with one element you always need a comma at the end of the first element.