How Can We Help?
Introduction:
In this tutorial, we are going to explain how to use Python iterate tuple by using for loops with basic syntax and many examples for better understanding.
How to iterate through tuple in Python ? To iterate through elements of tuple in python we can use loops like (for loop & while loop) .
Syntax:
for var in (tuple_variable_name) :
(for block)
Input Parameters:
- var : the variable that will hold each value of given tuple.
- tuple_variable_name : The tuples that we want to iterate through it.
iterate tuple using for loops
Example (1)
mytuple = (1,2,3,4)
for var in mytuple:
print("Index of Element :", mytuple.index(var) , " - Element of tuple:",var)
Output of example 1
Index of Element : 0 – Element of tuple: 1
Index of Element : 1 – Element of tuple: 2
Index of Element : 2 – Element of tuple: 3
Index of Element : 3 – Element of tuple: 4
In the above Example, using iteration, we fetched the index of each element in the tuple and the element of tuple (1,2,3,4) and print them together in separate lines.
iterate tuple using for loops and range
Example (2)
# example tuple
mytuple = (1, 2, 3, 4)
# getting length of tuple
lengthOfmytuple = len(mytuple)
# Iterating the index
for var in range(lengthOfmytuple):
print(mytuple[var])
Output of example 2
1
2
3
4
In the above Example, using for loops with rang, we iterate through the rang of our tuple “mytuple” then print each value of the tuple in a separate line.
iterate tuple using while loop
Example (3)
# example tuple
mytuple = [1, 2, 3, 4, 9, 10, 8]
# Getting length of tuple
lengthOfmytuple = len(mytuple)
i = 0
# Iterating through the tuple using while loop
while i < lengthOfmytuple:
print(mytuple[i])
i += 1
Output of example 3
1
2
3
4
9
10
8
In the above Example, using iteration with while loop, we fetched the element of tuple (1,2,3,4,9,10,8) and print them together in separate lines.
In this tutorial, you have learned how to iterate through tuple elements in python using for loop.
If you have an inquiry or doubt don’t hesitate to leave them in comment. we are waiting your feedback.But remember to understand the concept very well, you need to practice more.
Hopefully, it was clear and concise.
Similar Python operators:
- Concatenation(‘+’) : It adds two tuples.
- Membership(‘in’ & ‘not in’) : It returns True , if given element is present in tuple otherwise returns False.
- Repetition(‘*’) : It repeats element of tuple.
Python tutorials list:
- Python tutorials list : access all python tutorials.