Python loop over tuples
Python Tuple Loops
You can use Python’s for loop construct to iterate over the items in a tuple. Iteration can be accomplished by using the tuple as an iterator or by using an index.
Syntax
Python tuples provide an iterator object. To iterate over a tuple, use the for statement as follows:
for obj in tuple:
. . .
. . .
Example 1
The following example shows a simple Python for loop structure –
tup1 = (25, 12, 10, -21, 10, 100)
for num in tup1:
print (num, end = ' ')
It will produce the following output −
25 12 10 -21 10 100
Example 2
To iterate over the items in a tuple, obtain an integer range object “0” to “len-1”.
tup1 = (25, 12, 10, -21, 10, 100)
indices = range(len(tup1))
for i in indices:
print ("tup1[{}]: ".format(i), tup1[i])
It will produce the following output −
tup1[0]: 25
tup1 [1]: 12
tup1 [2]: 10
tup1 [3]: -21
tup1 [4]: 10
tup1 [5]: 100