Python - How to Iterate over a list object



Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    for i in range(a):
TypeError: 'list' object cannot be interpreted as an integer
>>> 


To iterate over the indices of a sequence i.e. List, you can combine range() and len() as follows: 

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
print(i,a[i])

0 Mary
1 had
2 a
3 little
4 lamb


however, it is convenient to use the function,enumerate() see Looping Techniques.

Comments

Popular posts from this blog

Python - How to Escape special characters in String

Python - Argument Passing