Table of Contents
ToggleLooping through tuple items in Python refers to iterating over each element in a tuple sequentially. This guide explores different looping techniques.
The for loop in Python allows iteration over a sequence, such as a tuple, by accessing each item individually.
tup = (25, 12, 10, -21, 10, 100)
for num in tup:
print(num, end=' ')
Output: 25 12 10 -21 10 100
The while loop is used to execute a block of code repeatedly as long as a condition evaluates to True.
my_tup = (1, 2, 3, 4, 5)
index = 0
while index < len(my_tup):
print(my_tup[index])
index += 1
Output:
1
2
3
4
5
Using an index allows access to tuple elements by iterating over a range corresponding to the tuple's length.
tup = (25, 12, 10, -21, 10, 100)
indices = range(len(tup))
for i in indices:
print("tup[{}]:".format(i), tup[i])
Output:
tup[0]: 25
tup[1]: 12
tup[2]: 10
tup[3]: -21
tup[4]: 10
tup[5]: 100
