How to iterate through a tuple in Python?

PythonServer Side ProgrammingProgramming

There are different ways to iterate through a tuple object. The for statement in Python has a variant which traverses a tuple till it is exhausted. It is equivalent to foreach statement in Java. Its syntax is −

for var in tuple:
stmt1
stmt2

Example

Following script will print all items in the list

T = (10,20,30,40,50)
for var in T:
print (T.index(var),var)

Output

The output generated is −

0 10
1 20
2 30
3 40
4 50

Another approach is to iterate over range upto length of tuple, and use it as index of item in tuple

Example

for var in range(len(T)):
  print (var,T[var])

You can also obtain enumerate object from the tuple and iterate through it.

Output

Following code too gives same output.

for var in enumerate(T):
  print (var)
raja
Published on 08-Jan-2018 19:42:59
Advertisements