Question 6.7: Iterating over a List You need to apply some lines of code t......

Iterating over a List

You need to apply some lines of code to each item in a list in turn.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

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.

Related Answered Questions

Question: 6.15

Verified Answer:

Use the for command to iterate over the keys of th...
Question: 6.14

Verified Answer:

Use the pop command, specifying the key for the it...
Question: 6.11

Verified Answer:

Use the Python language feature called comprehensi...
Question: 6.12

Verified Answer:

Use a Python dictionary. Arrays are great when you...
Question: 6.13

Verified Answer:

Use the Python [] notation. Use the key of the ent...
Question: 6.10

Verified Answer:

Use the [:] Python language construction. The foll...
Question: 6.9

Verified Answer:

Use the sort Python language command: >>&...
Question: 6.2

Verified Answer:

Use the [] notation to access elements of a list b...
Question: 6.3

Verified Answer:

Use the len Python function. For example: >&...