Enumerating a List
You need to run some lines of code to each item in a list in turn, but you also need to know the index position of each item.
Use the for Python language command along with the enumerate command.
>>> a = [34, ‘Fred’, 12, False, 72.3] >>> for (i, x) in enumerate(a): … print(i, x) … (0, 34) (1, ‘Fred’) (2, 12) (3, False) (4, 72.3) >>> |
Discussion
It’s quite common to need to know the position of something in the list while enumerating each of the values. An alternative method is to simply count with an index variable and then access the value using the [] syntax:
>>> a = [34, ‘Fred’, 12, False, 72.3] >>> for i in range(len(a)): … print(i, a[i]) … (0, 34) (1, ‘Fred’) (2, 12) (3, False) (4, 72.3) >>> |
See Also
All the recipes between Recipes 6.1 and 6.11 involve the use of lists.
See Recipe 6.7 to iterate over a list without needing to know each item’s index position.