Python: Editing list while iterating over it

若如初见. 提交于 2021-02-05 10:41:29

问题


There are some related questions on Stack but I wanted to be as clear as possible. I am using Python 3

If I have a list, N, and I use the following code:

N = [1,2,3,4,6,7,8]
for x in N:
    N[x] = N[x] * -1
return N

I am getting a Index out of range error. I understand you shouldn't be adding and deleting elements while iterating over a list, but I wanted a clear definition of why the above example won't work.To me, it seems like there shouldn't be a problem. In the first iteration, x should evaluate to 1. So if I want to edit N[1], I don't see why I wouldn't be able to.

As a side note, I know enumerate() is the proper way to do it.


回答1:


Use enumerate

Ex:

N = [1,2,3,4,6,7,8]
for x, value in enumerate(N):
    N[x] = value * -1
print(N)

or a list comprehension.

Ex:

N = [x * -1 for x in N]



回答2:


In for x in N:, x takes on each value in N, then you use it like an index. Lists in Python are 0-indexed, so you get an Index out of range error when you reach the end of the list and try to access N[8], which doesn't exist. You can use for x in range(len(N)): instead.




回答3:


The problem here is actually a little different: you're treating members of the list as if they were indices of the list. Since N[8] doesn't exist, that's where your error is coming from. I think what you meant to do was:

N = [1,2,3,4,6,7,8]
for x in range(len(N)):
    N[x] = N[x] * -1
return N



回答4:


In the first iteration, x=1 which means N[1] equals 2 and so your new N[1] becomes 2 * -1 = -2. Now when x is 8 since you are using for x in N, your code tries to access N[8] but since the length of N is 8, the indexing starts from 0 and goes up to 7. Hence there is no index 8 and hence you get an error Index out of range error




回答5:


Use good ol' lambda's or a specific callable in list comprehension:

lambda:

N = [1,2,3,4,6,7,8]
M = [(lambda x:-x)(element) for element in N]
print(M)

callable/function:

def negate(x):
    return -x

N = [1,2,3,4,6,7,8]
M = [negate(element) for element in N]
print(M)



回答6:


In your code here -

N = [1,2,3,4,6,7,8]
for x in N: 
# x will be 1, 2, 3, 4

And the way you are accessing is -

N[x]

But indices run from 0 to n-1, where n-1 is the last element. Also, in your list, you are missing a 5 so indices will change badly. If you had

N = [1,2,3,4,5,6,7,8]

your code would have worked fine. But since that's not the case, you'd have to use range like -

for i in range(len(N)):
    N[i] = N[i] * -1



回答7:


You are enumerating in a wrong way

N = [1,2,3,4,6,7,8]
for i, x in enumerate(N):
    N[i] = N[i] * -1
return N


来源:https://stackoverflow.com/questions/51633619/python-editing-list-while-iterating-over-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!