How to iterate through a list in Python?

PythonServer Side ProgrammingProgramming

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

for var in list:
  stmt1
  stmt2

Example

Following script will print all items in the list

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

Output

The output generated is −

0 10
1 20
2 30
3 40
4 50

Example

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

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

Output

You can also obtain enumerate object from the list and iterate through it. Following code too gives same output.

for var in enumerate(L):
  print (var)
raja
Published on 09-Jan-2018 04:47:25
Advertisements