Question 6.8: Enumerating a List You need to run some lines of code to eac......

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.

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 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.

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.7

Verified Answer:

Use the for Python language command: >>&g...
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: >&...