简体   繁体   中英

Change list, that you are iterating through, in that loop

In my case I have a for loop, looping through a list, but I want to change that list in said loop. After that I want the for loop to iterate through the new list.

li = [4,5,6,7,8,9]
for item in li:
    #do something

    if item == 5:
        #now continue iterating through this loop and not the old one
        li = [9,9,9,9,9,9] 

How can I do something like that?

Allthough @BoarGules's comment is correct, you may solve your problem using enumerate.

li = [4,5,6,7,8,9]
for i, item in enumerate(li):
    print(li[i])
    if li[i] == 5:
        li = [9,9,9,9,9,9]

This outputs:

>4
>5
>9
>9
>9

You shouldn't change the list through iteration. I would use indexing:

for i in range(len(li)):
    if li[i] == 5:
        li = len(li) * [9]

To see why this doesn't work, a for loop is equivalent to a while loop like this:

# for x in y:
#    ...
itr = iter(y)
while True:
    try:
        x = next(itr)
    except StopIteration:
        break
    ...

If you assign something new to y , the loop isn't affected, because it only uses the iterator over the original value assigned to y , not the name y itself.

However, if you do mutate the list in the body of the loop, the iterator might return a value you don't expect. If you need to change the iterable, it's best to get the iterator yourself.

li = [4,5,6,7,8,9]
itr = iter(li)
while True:
    try:
        item = next(itr)
    except StopIteration:
        break
    #do something

    if item == 5:
        #now continue iterating through this loop and not the old one
        itr = iter([9,9,9,9,9])

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