In this tutorial, learn how to iterate through tuple elements in Python. Get each individual element of tuple and print in the output with various looping methods.
Perform iteration with the for loop or the while loop to get individual elements. Check the sections given below with loop iteration and see the examples. If you don’t know about tuple then you may like to read how to create tuple in Python.
Iterate Through Tuple Elements Using For Loop in Python
You can perform the loop over the tuple elements using the for loop of Python. The for loop iterate each element of the tuple and prints the elements in every single line. The elements can be of any type like string or integers.
1 2 3 |
myTuple = ("Ram", 23, 10, "Dara", 17, "Raju"); for t in myTuple: print(t); |
Output
23
10
Dara
17
Raju
The above example showing the tuple elements with a single element in a single line. This is a simple for loop method for iteration through the tuple elements.
However, you can also use the while loop to iterate through each element of the tuple. You have to read further in the section to know the method with while loop.
Loop Through Tuple Elements Using While Loop in Python
The while loop using a different method from the for loop method. You have to first initialize a variable with zero(0). After that, you have to find the length of a tuple for continuous iteration.
See the example below to find the method of looping with while loop in Python.
1 2 3 4 5 |
myTuple = ("Ram", 23, 10, "Dara", 17, "Raju"); t=0; while t < len(myTuple): print(myTuple[t]) t += 1 |
Output
23
10
Dara
17
Raju
The above example prints the same output as you get with the for loop of Python. However, the method is different from the method of for loop. You can use both the above-given methods as per your requirement.
Iteration With Tuple Directly Without Tuple Variable
In addition to above all method, you can also perform the iteration over tuple element without the tuple variable. To perform this task, you have to pass the tuple directly in the for loop as given below.
1 2 |
for t in ("Ram", 23, 10, "Dara", 17, "Raju"): print(t); |
Output
23
10
Dara
17
Raju
The above example contains the same number of tuple elements as given above examples. This is the simple two-line code to perform an iteration over the tuple elements.
DOWNLOAD Free PYTHON CHEAT SHEET
You may also like to read
I hope you like this tutorial on how to iterate through the tuple elements with Python.
Reference
Stackoverflow Discussion on Python For Tuple Iteration