+ 1
How to remove 0 in a list?
I know only to remove 0 is easy, but in fact there are a lot of things like False, None, 0, [], {} and so on that are also removed when I run the line of code: list.remove(0) Is there a solution for that?
11 Antworten
+ 2
Interesting situation!
I suppose the problem is that you check for *equality*, and False in that sort of situation equals to 0.
One way around it: Check for *identity* instead!
list_ = [n for n in list_ if n is not 0]
This works because False may equal 0 but it *is not* 0.
+ 1
False = 0
0 = 0
it will remove both
print(False==0)
lst=[False, None, 0, [], {}]
print([x for x in lst if x != 0])
lst.pop(0)
lst.remove(0)
all have the same result, it might be beneficial to have all zeroes made into strings "0"
lst=[False, None, "0", [], {}]
print([x for x in lst if x != "0"])
+ 1
Steven M Thank you for helping to solve the problem.
0
Replacing list.remove(0) with list.remove(int(0)) will work.
But make sure you handle errors as it'll raise error if element doesn't exist anymore.
0
Shashi Ranjan but I tried and it still removes False as usual...
0
It shouldn't.
Kindly share the code.
0
Shashi Ranjan Here’s the code.
0
False is 0 and vice-versa so it'll be removed anyway. Instead use "False".
Here's the corrected version:
https://code.sololearn.com/ct54J2Wuat2K/?ref=app
0
Shashi Ranjan But False is still removed?