-1

I want to remove all the "1" from this list, but it keeps always the last one.

userlist = [1, 1, 1, 2, 1, 4, 1, 5, 1]

smallnumber = min(userlist)
[userlist.remove(x) for x in userlist if x == smallnumber] 

print(userlist)
Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
  • 1
    Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – buran Mar 20 '21 at 10:07
  • Anyway, it's better as `[x for x in userlist if x != smallnumber]` – buran Mar 20 '21 at 10:08

3 Answers3

0

A more elegant solution would be:

userlist_new = [x for x in userlist if x != min(userlist)]
rauberdaniel
  • 1,017
  • 9
  • 22
0

There is some answer for this, but you need to see where your wrong:

[userlist.remove(x) for x in userlist if x == smallnumber] 

you are using list.remove inside a list comprahention, this is as writing this:

new_list = []
for x in userlist:
   if x == smallnumber:
       new_list.append(userlist.remove(x))

as you can see list.remove return nothing, so the new_list will be full with None, and the userlist will be cleared from the number

I will add another solution:

list(filter((smallnumber ).__ne__, userlist))
Reznik
  • 2,663
  • 1
  • 11
  • 31
0

[userlist.remove(x) for x in userlist if x == smallnumber]

This line in your code is equivalent to below. * note the print(x) I have added to show you the point

for x in userlist:
    print(x)
    if x == smallnumber:
        userlist.remove(x)

The problem here is that you are trying to iterate through an object and at the same time removing the object from the list. This messes up the way python iterates through the loop. From above print you can see that python won't be traversing all the elements because of this.

So you should probably use some other logic. Few has already been suggested in the other answers. One another way is to use filters

filtered_list = list(filter(lambda x: x!=smallnumber, userlist))

If you want to change the orginal one itself. You can use below logic

for _ in range(userlist.count(smallnumber)):
    userlist.remove(smallnumber)
Ritwik G
  • 406
  • 2
  • 8