I entered a line of code
li = [1,2,3,4,5,6,7]
for i in li :
if i%2 == 0:
li.remove(i)
print(li)
[1, 3, 5, 7]
it's ok
two
li = [2,4,5,6,7]
for i in li :
if i%2 == 0:
li.remove(i)
print(li)
[4, 5, 7]
it's ok ,But I don't know why
three
li = [2,6,4,5,4,7]
for i in li :
if i%2 == 0:
li.remove(i)
print(li)
[6, 5, 7]
it's ok ,Same as the second one, but I do not know why
four
li = [2,6,4,5,6,7]
for i in li :
if i%2 == 0:
li.remove(i)
print(li)
[5, 6, 7]
I broke down
five
li = [2,6,5,6,6,7]
for i in li :
if i%2 == 0:
li.remove(i)
print(li)[5, 6, 6, 7]
😭😭😭
Sorry, I don't know English very much, with the help of Google Translate
Any help would be appreciated.
As @Lennart Regebro mentioned in his answer , since your modifying the list each time you 're iterating over it, it's safer to get a copy of that list and iterate over that copy, because you will get unexpected results otherwise:
li = [2,6,5,6,6,7]
for i in li[:]: #Notice the [:] notation, it is used to create a copy of a list.
if i%2 == 0:
li.remove(i)
print(li)
Result:
[5, 7]
You are modifying the list while looping over it which means after every number you remove the loop will avoid the first value after the removed value and take the second next value till the loop end.
You can make a copy of the list to iterate over and remove from the original one as follows:
li = [2,6,5,6,6,7]
li_copy = li.copy()
for i in li_copy :
if i%2 == 1:
li.remove(i)
print(li)
Ahmed Hawary has pointed out your mistake. You can also try this, list comprehension makes it very easy to modify existing list based on any condition.
[i for i in li if i%2!=0]
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.