Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to a Python list in terms of indexing, nested objects, and repetition but the main difference between both is Python tuple is immutable, unlike the Python list which is mutable.
Creating Python Tuples
There are various ways by which you can create a tuple in Python. They are as follows:
- Using round brackets
- With one item
- Tuple Constructor
Create Tuples using Round Brackets ()
To create a tuple we will use () operators.
Python3
var = ( "Geeks" , "for" , "Geeks" ) print (var) |
Output:
('Geeks', 'for', 'Geeks')
Create a Tuple With One Item
Python 3.11 provides us with another way to create a Tuple.
Python3
values : tuple [ int | str , ...] = ( 1 , 2 , 4 , "Geek" ) print (values) |
Output:
Here, in the above snippet we are considering a variable called values which holds a tuple that consists of either int or str, the ‘…’ means that the tuple will hold more than one int or str.
(1, 2, 4, 'Geek')
Note: In case your generating a tuple with a single element, make sure to add a comma after the element. Let us see an example of the same.
Python3
mytuple = ( "Geeks" ,) print ( type (mytuple)) #NOT a tuple mytuple = ( "Geeks" ) print ( type (mytuple)) |
Output:
<class 'tuple'>
<class 'str'>
Tuple Constructor in Python
To create a tuple with a Tuple constructor, we will pass the elements as its parameters.
Python3
tuple_constructor = tuple (( "dsa" , "developement" , "deep learning" )) print (tuple_constructor) |
Output :
('dsa', 'developement', 'deep learning')
What is Immutable in Tuples?
Tuples in Python are similar to Python lists but not entirely. Tuples are immutable and ordered and allow duplicate values. Some Characteristics of Tuples in Python.
- We can find items in a tuple since finding any item does not make changes in the tuple.
- One cannot add items to a tuple once it is created.
- Tuples cannot be appended or extended.
- We cannot remove items from a tuple once it is created.
Let us see this with an example.
Python3
mytuple = ( 1 , 2 , 3 , 4 , 5 ) # tuples are indexed print (mytuple[ 1 ]) print (mytuple[ 4 ]) # tuples contain duplicate elements mytuple = ( 1 , 2 , 3 , 4 , 2 , 3 ) print (mytuple) # adding an element mytuple[ 1 ] = 100 print (mytuple) |
Output:
Python tuples are ordered and we can access their elements using their index values. They are also immutable, i.e., we cannot add, remove and change the elements once declared in the tuple, so when we tried to add an element at index 1, it generated the error.
2
5
(1, 2, 3, 4, 2, 3)
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 11, in
tuple1[1] = 100
TypeError: 'tuple' object does not support item assignment
Accessing Values in Python Tuples
Tuples in Python provide two ways by which we can access the elements of a tuple.
- Using a positive index
- Using a negative index
Python Access Tuple using a Positive Index
Using square brackets we can get the values from tuples in Python.
Python3
var = ( "Geeks" , "for" , "Geeks" ) print ( "Value in Var[0] = " , var[ 0 ]) print ( "Value in Var[1] = " , var[ 1 ]) print ( "Value in Var[2] = " , var[ 2 ]) |
Output:
Value in Var[0] = Geeks
Value in Var[1] = for
Value in Var[2] = Geeks
Access Tuple using Negative Index
In the above methods, we use the positive index to access the value in Python, and here we will use the negative index within [].
Python3
var = ( 1 , 2 , 3 ) print ( "Value in Var[-1] = " , var[ - 1 ]) print ( "Value in Var[-2] = " , var[ - 2 ]) print ( "Value in Var[-3] = " , var[ - 3 ]) |
Output:
Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] = 1
Different Operations Related to Tuples
Below are the different operations related to tuples in Python:
- Concatenation
- Nesting
- Repetition
- Slicing
- Deleting
- Finding the length
- Multiple Data Types with tuples
- Conversion of lists to tuples
- Tuples in a Loop
Concatenation of Python Tuples
To Concatenation of Python Tuples, we will use plus operators(+).
Python3
# Code for concatenating 2 tuples tuple1 = ( 0 , 1 , 2 , 3 ) tuple2 = ( 'python' , 'geek' ) # Concatenating above two print (tuple1 + tuple2) |
Output:
(0, 1, 2, 3, 'python', 'geek')
Nesting of Python Tuples
A nested tuple in Python means a tuple inside another tuple.
Python3
# Code for creating nested tuples tuple1 = ( 0 , 1 , 2 , 3 ) tuple2 = ( 'python' , 'geek' ) tuple3 = (tuple1, tuple2) print (tuple3) |
Output :
((0, 1, 2, 3), ('python', 'geek'))
Repetition Python Tuples
We can create a tuple of multiple same elements from a single element in that tuple.
Python3
# Code to create a tuple with repetition tuple3 = ( 'python' ,) * 3 print (tuple3) |
Output:
('python', 'python', 'python')
Try the above without a comma and check. You will get tuple3 as a string ‘pythonpythonpython’.
Slicing Tuples in Python
Slicing a Python tuple means dividing a tuple into small tuples using the indexing method.
Python3
# code to test slicing tuple1 = ( 0 , 1 , 2 , 3 ) print (tuple1[ 1 :]) print (tuple1[:: - 1 ]) print (tuple1[ 2 : 4 ]) |
Output:
In this example, we sliced the tuple from index 1 to the last element. In the second print statement, we printed the tuple using reverse indexing. And in the third print statement, we printed the elements from index 2 to 4.
(1, 2, 3)
(3, 2, 1, 0)
(2, 3)
Note: In Python slicing, the end index provided is not included.
Deleting a Tuple in Python
In this example, we are deleting a tuple using ‘del’ keyword. The output will be in the form of error because after deleting the tuple, it will give a NameError.
Note: Remove individual tuple elements is not possible, but we can delete the whole Tuple using Del keyword.
Python3
# Code for deleting a tuple tuple3 = ( 0 , 1 ) del tuple3 print (tuple3) |
Output:
Traceback (most recent call last):
File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in <module>
print(tuple3)
NameError: name 'tuple3' is not defined
Finding the Length of a Python Tuple
To find the length of a tuple, we can use Python’s len() function and pass the tuple as the parameter.
Python3
# Code for printing the length of a tuple tuple2 = ( 'python' , 'geek' ) print ( len (tuple2)) |
Output:
2
Multiple Data Types With Tuple
Tuples in Python are heterogeneous in nature. This means tuples support elements with multiple datatypes.
Python3
# tuple with different datatypes tuple_obj = ( "immutable" , True , 23 ) print (tuple_obj) |
Output :
('immutable', True, 23)
Converting a List to a Tuple
We can convert a list in Python to a tuple by using the tuple() constructor and passing the list as its parameters.
Python3
# Code for converting a list and a string into a tuple list1 = [ 0 , 1 , 2 ] print ( tuple (list1)) # string 'python' print ( tuple ( 'python' )) |
Output:
Tuples take a single parameter which may be a list, string, set, or even a dictionary(only keys are taken as elements), and converts them to a tuple.
(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')
Tuples in a Loop
We can also create a tuple with a single element in it using loops.
Python3
# python code for creating tuples in a loop tup = ( 'geek' ,) # Number of time loop runs n = 5 for i in range ( int (n)): tup = (tup,) print (tup) |
Output:
(('geek',),)
((('geek',),),)
(((('geek',),),),)
((((('geek',),),),),)
(((((('geek',),),),),),)