简体   繁体   中英

Why does cycle 'if' delete not all odd numbers from the list (only each second odd number)?

There is a code:

list = [1, 2]

while list[-1]+list[-2] <= 4000000:
    list.append(list[-1] + list[-2])
for i in list:
    if i % 2 == 1:
        print(i)
        list.remove(i)
print(list)
print(sum(list))

You shouldn't modify a list (or any container) while iterating through it.

One way to go around it is to use another container,

in_list = [1, 2]

while in_list[-1]+in_list[-2] <= 20:
    in_list.append(in_list[-1] + in_list[-2])

print(in_list)

out_list = []
for i in in_list:
    if i % 2 != 1:
        print(i)
        out_list.append(i)

print(out_list)
print(sum(out_list))

This code uses a different approach than yours: it creates the input list, then while iterating it adds the even elements to a new, output list. This has the same effect as removing the odd elements from the input list, however, it doesn't break the iteration by modifying the input list.

Like said in the comments, you shouldn't use built-in names ("list") for your variable names - it will shadow them. Also, when you develop and debug your code it's best to stick to smaller examples. Here I use 20 instead of 4,000,000 - much easier to track and doesn't lose the meaning.

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