Python - Loop Lists


You can traverse the items in a list with Python's for loop construct. The traversal can be done, using list as an iterator or with the help of index.

Syntax

Python list gives an iterator object. To iterate a list, use the for statement as follows −

for obj in list:
   . . .
   . . .

Example 1

Take a look at the following example −

lst = [25, 12, 10, -21, 10, 100]
for num in lst:
   print (num, end = ' ')

Output

It will produce the following output

25 12 10 -21 10 100

Example 2

To iterate through the items in a list, obtain the range object of integers "0" to "len-1". See the following example −

lst = [25, 12, 10, -21, 10, 100]
indices = range(len(lst))
for i in indices:
   print ("lst[{}]: ".format(i), lst[i])

Output

It will produce the following output

lst[0]: 25
lst[1]: 12
lst[2]: 10
lst[3]: -21
lst[4]: 10
lst[5]: 100
Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements