Python tuples are the immutable data structure which can accommodate data of various datatypes. After you have learnt about Python List in our previous tutorial, this is time to understand tuples in Python.
Table of contents
- What are Python tuples
- How to create tuples in Python
- Add element(s) in python tuples
- Basic tuples operation
- How to access elements from tuples in Python
- Convert List to Tuple in Python
- Convert Tuple to List in Python
- Common Python function associated with tuples in Python
- List vs Tuple in Python
- Conclusion
What are Python tuples
A tuple is ordered collection of heterogeneous data similar to Python List datastructure but tuple is Immutable (unchangeable). As you know, List is mutable. Any element can be modified, deleted or added to an existing list whereas once tuple is created, it can not be modified.
In a real-world scenario, Keys on TV remote control resembles with Tuple. These keys are fixed at a specific position (in an ordered way) at the time of its creation (manufacturing) and it can’t be changed further. We need Tuple in such scenarios, where data has to be fixed and code does not allow any change.
For example, We don’t want the month’s name as well as the order in which they appear, to be changed.
How to create tuples in Python
Tuples in Python are very simple to create. Following example demonstrates one-liner method to create tuples.
To create an empty tuple in Python. Create any variable to hold tuple (in this example, tup1) and just open and close normal (round) bracket.
tup1 = ( )
To create a tuple with some value in it, we can create it in the following way. Create a variable (tup2 or any other name you like) and write values separated by a comma. In this case, we are using week name (which is a string), thus need to be inside double quotes (” “). If it is not a string then we can simply write as shown in tup3.
tup2 = (“Mon”, “Tue”, “Wed”, "Thu", "Fri", "Sat", "Sun")
tup3 = (1, 6, 7, 8, 10 )
We can also use float data type or even mixed data type to create Tuple in Python.
tup4 = (6.5, 1.9, 3.14 )
tup5 = (“aipython”, 2019, 21.52 )
Add element(s) in python tuples
Till now, we have learned to create a tuple with some value, but what if we want to add some element to it. Unlike a list, we can’t add a numeric, string or any other data type to a tuple. However, we can do so in some other way as shown below.
Adding a single element to Tuple
We can’t add a single element to a tuple directly, but we can convert a single element to the tuple and then add it to an existing tuple.
# Let say, tup6 is a tuple
tup6 = (1, 2, 3, 4, 5)
# First, we will try to add an integer 6 to this tuple, as shown below
tup7 = tup6 + 6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "int") to tuple
Now, we will add the same number but make it tuple first and then add it to an existing tuple, as shown below
tup7 = tup6 + (6,)
print (tup7)
(1, 2, 3, 4, 5, 6)
Note that, we have used comma (,), in order to convert integer 6 to a tuple. If you directly use tup6+(6) then again you will see an error, as (6) alone is an integer even though it is enclosed inside a normal bracket. A comma is required only when there is a single element.
Adding multiple elements to Tuple
To add more than one element, the comma is optional while writing new tuple. we can write the expression as shown below.
tup8 = tup7+ (10, 11, 12) # we can also write -> tup8 = tup7 + (10, 11, 12, )
print (tup8)
(1, 2, 3, 4, 5, 6, 10, 11, 12)
Basic tuples operation
In the previous section, you have learned to add single or multiple elements to a tuple. Now you will learn various other tuple operations. Python operators work well with a tuple.
Tuple addition (adding two tuples in Python)
tuple1 = ( 0, 1, 2, 3 )
tuple2 = (‘welcome', ‘aipython')
print ( tuple1 + tuple2 )
( 0, 1, 2, 3, ‘welcome’, ‘aipython’ )
Tuple Multiplication
Observe the two multiplication results, you will notice little variations and this is because of an extra comma (,) at the end of the element.
print( ('python’) * 3 )
( ‘pythonpythonpython’ )
print ( ('python’ ,) * 3 )
( ‘python’, ‘python’, ‘python’ )
Tuple Packing
Tuple packing refers to combining two different tuples in one tuple but without mixing all the elements. The actual tuple still resides inside a new tuple as a separate entity, as shown below.
tuple4 = (tuple1, tuple2)
print(tuple4)
( (0, 1, 2, 3), (‘welcome’, ‘aipython’) )
Tuple Membership
Definition of the membership function is same throughout Python programming language. Membership operator in Python is denoted by “in“. Membership function checks for the presence of a specified value in the tuple and returns True if the value is present otherwise False.
new_tuple = (‘p’, ’y’, ’t’, ’h’, ’o’, ‘n’)
>>> ‘h' in new_tuple
True
>>> 'a' in new_tuple
False
Tuple Mutation (Update tuple element)
By far you must have understood that Python tuples are non-mutable, unlike the List. In the list, we can update the value of an element but the Tuples element can not be updated (or edited).
If you want to update the element via list like update method then you will get an error message as shown below.
tuple1 = ( 0, 1, 2, 3 )
Tuple1 [0] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Underline information: Tuple is non-mutable.
How to access elements from tuples in Python
Elements in the tuple are accessed in the same way as in List. The example is shown below clearly illustrate the element access in Tuples.
my_tuple = (0 ,1, 2, 3)
my_tuple [ 0 ] --> 0 # returns the 0th element
my_tuple [ -1 ] --> 3 # returns the last element
my_tuple [ 1 : ] --> 1, 2, 3 # returns element from index 1 till end
my_tuple [ :: -1 ] --> 3,2,1,0 # reverse the order
my_tuple [ 1 : 3 ] --> 1, 2 # returns from index 1 till 3, but not includes 3rd index
Sequence unpacking in Python Tuples
First, understand the unpacking in Tuple. It is basically assigning each variable one element. This is suitable especially for very small Tuples, as shown below.
my_tuple = (0 ,1, 2, 3)
a, b, c, d = my_tuple
>> a = 0, b= 1, c=2, d=3
The sequence unpacking method is the same as that of the list. In sequence unpacking the elements are extracted from the large tuple and are assigned to few elements. The “*” asterisk symbol is placed before a variable name. Each variable gets assigned with the value as per their order and the variable preceded with “*” symbol hold the remaining value, as shown below. Also, notice that the unpacked value in “p” is a list.
a, *p = my_tuple
>> a= 0, b = [1,2,3]
Convert List to Tuple in Python
A list can easily be converted (or transformed) into a tuple by following method. Once the list is converted to a tuple, the element can not be modified, replaced or deleted.
Syntax: tuple (any_list)
my_list = [1, 2, 3, 4]
new_tuple = tuple(my_list)
print (new_tuple)
(1, 2, 3, 4)
List inside a tuple
There are scenarios where a list can reside inside a Tuple. In such case only the elements of a list (which is inside a tuple), are mutable.
t1 = (1, 2, 3, [4, 5, 6])
print (t1[3][1])
5
# We can modify the elements of this list
t1[3][1] = 10
print (t1)
(1, 2, 3, [4, 10, 6])
Tuple inside a List
In Python programming, you will observe a tuple inside a list. Sometimes, it is required to place fixed elements inside a list and we can do that by utilizing tuple characteristics (immutable). Let, us see by an example
L1 = [1, 2, 3, 4, (5, 6)]
print (L1[4][0])
5
# we can not modify some of elements even though it is inside list, Here tuple is freezed
L1[4][0] = 8 # here it is not possible to replace the element 5 with 8, it will throw error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Convert Tuple to List in Python
A tuple can easily be converted (or transformed) into a list by following method. Once a tuple is converted to a list, the element can be modified, replaced or even deleted.
Syntax: list(any_tuple)
my_tuple= (1, 2, 3, 4)
new_list = list(my_tuple)
print (new_list)
[1, 2, 3, 4]
Common Python function associated with tuples in Python
There are a few handy functions that you would like to use while working with Python Tuples.
Let say, we have a tuple with name t1 and t1 = (1, 2, 3, 4, 5, 6, 7)
The table below shows various function applicable to the tuple (t1), the result and function description.
Function | Result | Description |
---|---|---|
len ( t1 ) | 6 | Calculates the length i.e. the total number of elements in the tuple |
min ( t1) | 1 | This will result in minimum value inside a tuple |
max (t1 ) | 7 | This will result in maximum value inside a tuple |
t1.index(4) | 3 | Returns the index of the first item that is equal to 4 |
t1.count(5) | 1 | Returns the number of items 5 |
del t1 | — | Will Finish the game (It will delete the Tuple (t1) |
List vs Tuple in Python
The table shown below outlines the difference between List and Tuple in Python.
List | Tuple |
---|---|
A list is defined by a square bracket [ ] | A tuple is defined by the () normal round bracket |
List is mutable | Tuple is immutable |
Keys in a dictionary can’t be a list | Keys in a dictionary can be a tuple |
There are 46 methods associated with List in Python. | There are 33 methods associated with Tuple in Python. |
Occupy more memory than tuple for the exact same number of element | Occupy less memory than a list for the exact same number of element |
Conclusion
After reading this article you have understood about Python tuples in details. As you have learnt about creating tuples, adding one or more elements, accessing elements, various tuple operations such as addition, multiplication, sequence unpacking, membership function and others. You have also learned to convert a tuple to list and vice versa. Additionally, this tutorial also taught some handy and easy to use tuple functions. Finally, you have seen the difference between Python tuple and list.
I am sure that by now you have understood the topic and gained the experience. I would suggest practising on Python tuples and solve some of the online problems. The more you practice more you learn.
Keep Learning and Keep growing.