In this Python tutorial, we will learn how to define a tuple, access elements of a tuple, and how to iterate over the elements of a tuple, with some examples.
Define a Python Tuple
Python Tuple is a collection of elements where elements can be accessed using index and are unchangeable.
What does this mean?
A tuple can be defined with a definite number of elements that belong to different datatypes.
Each member can be accessed using the index. index starts with 0 for the first element and increments for the subsequent elements.
You cannot modify a tuple, hence unchangeable.
How to define Python Tuple?
To define a Python Tuple, use parenthesis ()
, and the elements inside these parenthesis separated by comma.
For example (14, "Raghu")
is a Tuple.
tuple1 = (14, 'Raghu')
You can access the first element using index as tuple1[0]
and the second element as tuple1[1]
.
Access Items of Tuple
In the following example, we define a tuple with an integer and string.
Also, we will access the individual elements using index.
example.py
myTuple = (14, 'Raghu')
print(myTuple[0])
print(myTuple[1])
Output
14
Raghu
Python Tuples are unchangeable
In the following example, we define a tuple with an integer and string.
We will try to change the elements of this tuple.
example.py
myTuple = (14, 'Raghu')
myTuple[0] = 25
myTuple[1] = 'Tim'
Output
Traceback (most recent call last):
File "example1.py", line 3, in <module>
myTuple[0] = 25
TypeError: 'tuple' object does not support item assignment
Yeah. Python Tuple does not support item assignment and hence unchangeable.
Iterate over Tuple
In the following example, we define a tuple with an integer and string.
We will try to iterate over the elements of this tuple.
example.py
myTuple = (14, 'Raghu')
for element in myTuple:
print(element)
Output
14
Raghu
Conclusion
In this Python Tutorial, we learned what a Python Tuple is, how to define a tuple, how to access the elements of a tuple and how to iterate over tuple.