Iterate Through A Tuple In Python

Iterate Through A Tuple In Python

We have been exploring tuples, and we have seen many different things, like how to create tuples, how to access the elements from the tuple, and much more. Now, we are going to explore how we can iterate through the tuple. Basically, iterating through a tuple simply can be understood as going through the tuple elements. At times, we might need to iterate through the tuple, and one of the ways to do this is by using loops. Let’s have a look at the below program, which demonstrates how we can iterate through the tuple using a loop. We are going to make use of a for loop here.

Iterate Through A Tuple In Python

As you can see in the above program, we have a simple tuple, and then we are trying to loop through the tuple. Here, the thing is that in every iteration, the element variable has one item from the tuple. So, in the first iteration, the element has 2, then in the next iteration, it has 9, and so on. Let’s have a look at the output of the above program.

2
9
3.1
GyaniPandit
True

As you can see, we have one item in each iteration from the tuple, with the element variable. So,

whenever we need to loop through the tuple, we can do so like we did in the previous example. But here, again, assigning any values to the element variable in the loop, won’t affect the tuple elements.

We can also make use of the range function, to access the elements with the indexes, but still, if we try to access them with the indexes, and then try to make changes in the tuple directly, we willget into an error. Let’s have a look at a simple program, which demonstrates the same thing.

As you can see in the above program, we have a simple tuple, and we are trying to loop through the tuple. This time, we are making use of the range function, and we are trying to access the elements with the help of their indexes. Also, we are making use of the len function, to get the length of the tuple. In this way, we are able to loop through the tuple, with help of the indexes of the elements.

You can also make use of the while loop, to iterate through the tuple. Let’s have a look at a simple program, which demonstrates the same thing.

As you can see in the above program, we have made use of the while loop, to loop through the tuple. Remember that here, we first have the index as zero, and then we are executing while loop, till the end of the tuple. In the while loop, we are printing the element, use the index, and then we are incrementing the index.