简体   繁体   中英

IndexError: list assignment index out of range.

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)

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.

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)

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM