0

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.

rpanai
  • 12,515
  • 2
  • 42
  • 64
  • Look on stackoverflow for questions with "how to delete or remove list elements in a loop" in Python. This has often been asked. Short answer: You can't, because it breaks your loop. – mkiever Mar 07 '19 at 14:12
  • 2
    Possible duplicate of [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – A Jar of Clay Mar 07 '19 at 14:18

3 Answers3

2

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]
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
0

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
  • 461
  • 4
  • 15
0

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]

  • 1
    If you surround your code with grave marks (looks like an apostrophe, but slightly different), it sets the code off like this `[i for i in li if i%2!=0]` – Acccumulation Mar 07 '19 at 16:04