The tuple data type is almost identical to the list data type, except in two ways.
First, Tuples are immutable i.e once a tuple is created, it can not be modified and second, tuples are enclosed with parenthesis ( ).
Creating an empty tuple
t0 = () print(type(t0)) # <class 'tuple'>
To create a tuple with a single element, you must include a comma:
t1 = ('john',) # not t1 = ('john') # This is interpreted by python as a string
Another way of creating a tuple is with the in-built
tuple() function :
t = tuple('john', 'doe', 17) print(t) # ('john', 'doe', 17) t0 = tuple(range(4)) print(t0) # (0, 1, 2, 3)
The elements of a tuple can be of different data types:
t = (1, 'a', 'b', 'c', 'd', 4, True, 5.44)
Elements in a tuple can be accessed via their index just like lists:
t = ('a', 'b', 1, 2, 6, 'r') t # 1 print(t) # a
dimension = (200, 50, 40) dimension = 60 # results in an error
The statement on the second line
dimension = 60 tries to change the value of the first
dimension, but Python returns a type error.
Basically, because we’re trying to alter a tuple, which can’t be done to that type of object, Python tells us we can’t assign a new value to an item in a tuple :
Traceback (most recent call last): File "dimensions.py", line 2, in <module> dimension = 60 TypeError: 'tuple' object does not support item assignment
Slicing a Tuple
t = ('a', 'b', 1, 2, 6, 'r') t_slice = t[1:4] print(t_slice) # ('b', 1, 2)
Converting a tuple to a list
l = list(('a', 'b', 1, 2, 6, 'r')) print(l) # ['a', 'b', 1, 2, 6, 'r']
Looping through a tuple
t = ("john", 'mike', 'doe', 'hermione') for name in t: print('hello ' + name) # output hello john hello mike hello doe hello hermione
The tuple data type can prove useful in many cases.
- Tuples are used to create multiple variables at once
(a , b, c) = ('john', 23, False) print(a) # john print(b) # 23 print(c) # False
- Tuples are conveniently used to swap variable values
name = 'john doe' age = 23 # swapping (name, age) = (age, name) print(name) # 23 print(age) # john doe
- Tuples can allow functions to return more than a single value
def compute(a, b): add = a + b sub = a - b return a, b # returns a tuple t = compute(8, 3) print(t) # (8, 3)