0

The following code raises an IndexError, can anyone explain why the logic of this code does not work?

midterms = [90, 80, 89, 87, 97, 100]
for mark in midterms:
    newMark = mark + 2
    midterms[mark] = newMark
print(midterms)

3 Answers 3

3

Because you're using the values contained in the list as indices; mark takes the values 90, 80, ..., 100. The subscription midterm[90] is obviously out of bounds.

To iterate through the items while also having a handle on the position, Python offers enumerate which provides an index along with the current value:

midterms = [90, 80, 89, 87, 97, 100]
for ind, mark in enumerate(midterms):
    newMark = mark + 2
    midterms[ind] = newMark
print(midterms)

This, in effect, allows iterating through the list and changing it effortlessly.

Sign up to request clarification or add additional context in comments.

2 Comments

I guess you could also use the range(len(midterms)) function.
@Jerrybibo you could be you really shouldn't. This is exactly why enumerate exists.
1

Another way to think of this if you're new to python (I didn't know about enumerate as a beginner) is to use Jerrybibo's suggestion. Code for that would look like this:

midterms = [90, 80, 89, 87, 97, 100]
for i in range(len(midterms)):
    newMark = midterms[i] + 2
    midterms[i] = newMark
print(midterms)

Comments

0

Jim Fasarakis-Hilliard and I share the same answer. Another workaround for your code is this:

midterms = [90, 80, 89, 87, 97, 100]
print [mark+2 for mark in midterms]

which shall also yield

[92, 82, 91, 89, 99, 102]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.