In this section, we will learn how to loop through the elements of a tuple in Python.
Python Iterate Tuple: How to Iterate Through a Tuple in Python?
Tuples are iterable in Python. That means we can use `while` and `for` loop to iterate through the elements of such object.
Alright now let’s see how to use for and while loops to run the loop operation on top of tuples.
Python for in Tuple
Using `for in` loop, we can set a tuple object as the iterable object and then take its entire elements one at a time and run a block of code for each element.
Example: Python Loop through Tuple via for Loop
tup1 = ("Ellen","Jack", "Omid","Elon", "James","Richard","Jeremy", "Ian", "Kimberly") for element in tup1: print(element)
Output:
Ellen Jack Omid Elon James Richard Jeremy Ian Kimberly
Python for Loop with Index Number Example:
Another method of looping through the elements of a tuple object is by using the `range()` function as well as the `len()` function.
Basically, we can create a sequence of numbers using the range() function with the maximum number of `leng(targetTupleObject)` and then use the name of the tuple object and a pair of brackets `[]` to get the elements of a tuple object.
tup1 = ("Ellen","Jack", "Omid","Elon", "James","Richard","Jeremy", "Ian", "Kimberly") for num in range(len(tup1)): print(tup1[num])
Output:
Ellen Jack Omid Elon James Richard Jeremy Ian Kimberly
Iterate Through Tuple Python via while Loop Example:
tup1 = ("Ellen","Jack", "Omid","Elon", "James","Richard","Jeremy", "Ian", "Kimberly") num =0 size = len(tup1) while(num<size): print(tup1[num]) num +=1
Output:
Ellen Jack Omid Elon James Richard Jeremy Ian Kimberly