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)
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)
A more elegant solution would be:
userlist_new = [x for x in userlist if x != min(userlist)]
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))
[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)