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.

Using for-in loop
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.

# define a tuple
t = ('iterating','a','tuple','is','easy')
# loop over it
for e in t:

This prints


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.

Index using enumerate()
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.

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):

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.

Hope this article on tuple iteration was useful.

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.