Question 6.2: Accessing Elements of a List You want to find individual ele......

Accessing Elements of a List

You want to find individual elements of a list or change them.

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 [] notation to access elements of a list by their position in the list. For example:

>>> a = [34, ‘Fred’, 12, False, 72.3]
>>> a[1]
‘Fred’

Discussion

The list positions (indices) start at 0 for the first element.

As well as using the [] notation to read values out of a list, you can also use it to change values at a certain position. For example:

>>> a = [34, ‘Fred’, 12, False, 72.3]
>>> a[1] = 777
>>> a
[34, 777, 12, False, 72.3]

If you try to change (or, for that matter, read) an element of a list using an index that is too large, you will get an “Index out of range” error:

>>> a[50] = 777
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
IndexError: list assignment index out of range
>>>

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

Verified Answer:

Use the for Python language command: >>&g...
Question: 6.3

Verified Answer:

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