简体   繁体   中英

Python for loop in enumerate list goes for infinite

I have a list of numbers and I want to run a for-loop through it, but as I update the list, the for loop does not stop and runs infinite time, here is my code:

a = [0,1,2,3,4,5,6]
for index, item in enumerate(a):
   if item>0:
       a.insert(index,10)

What should I do to just update and insert into list "a" and just doing for loop for pre defined list before adding new items?

Is that what you are looking for? (it is not clear..)
The code replaces every positive value with 10

a = [0, 1, 2, 3, 4, 5, 6]
a1 = [10 if x > 0 else x for x in a]
print(a1)

output

[0, 10, 10, 10, 10, 10, 10]

您可以遍历此列表的副本:

for index, item in enumerate(a.copy()):

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