Iterating over a List
You need to apply some lines of code to each item in a list in turn.
Use the for Python language command:
>>> a = [34, ‘Fred’, 12, False, 72.3] >>> for x in a: … print(x) … 34 Fred 12 False 72.3 >>> |
Discussion
The for keyword is immediately followed by a variable name (in this case, x). This is called the loop variable and will be set to each of the elements of the list specified after in.
The indented lines that follow will be executed one time for each element in the list. Each time around the loop, x will be given the value of the element in the list at that position. You can then use x to print out the value, as shown in the previous example.
See Also
All the recipes between Recipes 6.1 and 6.11 involve the use of lists.