A python tuple is a collection of elements enclosed between parenthesis. Since it is a collection, it is required to loop or iterate over a tuple to access its elements.
This article will explain how to iterate a python tuple with example programs.
A for loop along with
in
operator is used to iterate over a tuple. Syntax of for-in
loop is for element in tuple: // more code
where element
is a variable that contains a tuple item in every iteration.
Example,
# define a tuple t = ('iterating','a','tuple','is','easy') # loop over it for e in t: print(e)
This prints
iterating
a
tuple
is
easy
Iterating with index
Many times we also need the index of tuple elements but with the for-in
loop shown above, the index is not directly available.
For getting the index, we will iterate using a for
loop with range()
function. Argument to range()
function will be the length of tuple so that the loop will iterate from 0 till the tuple length.
To determine the length of tuple, we can use Python’s inbuilt len() function.
Complete example is given below.
# create tuple t = ('iterating','a','tuple','is','easy') # iterate tuple for i in range(len(t)): print('Index:',i, ',Element:',t[i])
This prints
Index: 0 ,Element: iterating
Index: 1 ,Element: a
Index: 2 ,Element: tuple
Index: 3 ,Element: is
Index: 4 ,Element: easy
Note that tuple elements are accessed using index enclosed between square brackets.
Another way to get the index of tuple elements is using Python’s inbuilt enumerate() function.
This function attaches a numeric index to the tuple elements starting from 0.
Example,
t = ('iterating','a','tuple','is','easy') for i,e in enumerate(t): print('Index:',i, ',Element:',t[i])
Note that this method can also be used to iterate over a tuple.
If you do not want the index but only the tuple element during iteration, then drop the index altogether as shown below.
t = ('iterating','a','tuple','is','easy') for e in enumerate(t): print(e[1])
As stated before, enumerate()
attaches a numeric index to each tuple item and returns another tuple whose first item is the index and second is the tuple element on which we are iterating.
Thus, to access the tuple element, we are using a numeric index of 1(which means the second element of the tuple returned by enumerate()
)
To learn about enumerate()
in great detail, visit this article.