+ 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?

23rd Feb 2019, 11:46 AM
Alice
Alice - avatar
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.
23rd Feb 2019, 5:45 PM
HonFu
HonFu - avatar
+ 1
Alice yes bcz it's considered as 0 and 0 in python.
23rd Feb 2019, 12:23 PM
Шащи Ранжан
Шащи Ранжан - avatar
+ 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"])
23rd Feb 2019, 2:14 PM
Steven M
Steven M - avatar
+ 1
Steven M Thank you for helping to solve the problem.
23rd Feb 2019, 2:20 PM
Alice
Alice - avatar
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.
23rd Feb 2019, 11:54 AM
Шащи Ранжан
Шащи Ранжан - avatar
0
Shashi Ranjan but I tried and it still removes False as usual...
23rd Feb 2019, 11:58 AM
Alice
Alice - avatar
0
It shouldn't. Kindly share the code.
23rd Feb 2019, 11:59 AM
Шащи Ранжан
Шащи Ранжан - avatar
0
Shashi Ranjan Here’s the code.
23rd Feb 2019, 12:05 PM
Alice
Alice - avatar
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
23rd Feb 2019, 12:17 PM
Шащи Ранжан
Шащи Ранжан - avatar
0
Shashi Ranjan But False is still removed?
23rd Feb 2019, 12:20 PM
Alice
Alice - avatar