Python loop through a tuple
In Python when we loop through a tuple using 'for' loop, we can fetch each element of a tuple with each iteration. Consider the following to know more.
Loop through a tuple with 'for' loop
The 'for' loop in Python is different form the 'for' loop in the other programming languages.
In Python, the 'for' loop does not require any update to be done. It automatically update after each iteration.
Python 'for' loop syntax
for variable in tuple_name:
statements
Example
Input
a = (1, 2, 3, 4, 5)
for i in a:
print(i)
Output
1
2
3
4
5
2
3
4
5
'for' loop over tuple with range() method
Loop over a tuple, like above can be done with the range() method.
Program
Input
a = (1, 2, 3, 4, 5)
length = len(a)
for i in range(0, length):
print(a[i])
Output
1
2
3
4
5
2
3
4
5
In looping over a tuple, range() method gives us the flexibility to select the particular range in tuple.
3
4
5
Program
Input
b = (1, 2, 3, 4, 5, 6, 7, 8, 9)
for j in range(2, 5):
print(b[j])
Output
3
4
5
Interval can be introduced while looping over a tuple with the range() method.
b = (1, 2, 3, 4, 5, 6, 7, 8, 9)
Program
Input
b = (1, 2, 3, 4, 5, 6, 7, 8, 9)
length = len(b)
for step in range(0, length, 2):
print(b[step])
Output
1
3
5
7
9
'for' loop over tuple with enumerate() method
The enumerate() method enumerates the tuple, with numbers.
Following is an example to enumerate the tuple.
Program
>>> b = (1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> list(enumerate(b))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
Here is an example, how you can fetch the content, got after enumerating the tuple. Both, tuple value and the enumerated value.
Program
Input
b = (1, 2, 3, 4, 5, 6, 7, 8, 9)
for i, j in list(enumerate(b)):
print("Index: ", i, " Value: ", j)
for i, j in list(enumerate(b)):
print("Index: ", i, " Value: ", j)
Output
Index: 0 Value: 1
Index: 1 Value: 2
Index: 2 Value: 3
Index: 3 Value: 4
Index: 4 Value: 5
Index: 5 Value: 6
Index: 6 Value: 7
Index: 7 Value: 8
Index: 8 Value: 9
Post a Comment
If you have any query, feel free to ask.