I have a list of lists in python that looks like this:
my_list = [[True, 0, 4], [True, 3, 6, 7], [1, 3, 5]]
And I want to remove all lists that have True in them
I tried with
my_list = [x for x in my_list if True not in x]
but all I get is an empty list when obviously the result should be [1, 3, 5]
When I try with a list like l = [[True, 0, 4], [3, 6, 7], [1, 3, 5]]
i get [[3, 6, 7]]
and I don't understand why.
It seems to be a problem with True because when I try with an integer it removes the lists accordingly
As @LydiavanDyke notes, True == 1
, so you would need to use the stronger is
operator, which means you cannot use the simple in
operator (which uses ==
).
my_list = [[True, 0, 4], [True, 3, 6, 7], [1, 3, 5]]
without_true = [
sublist for sublist in my_list
if not any(item is True for item in sublist)
]
will then give you
>>> without_true
[[1, 3, 5]]
note that A in B
is functionally equivalent to (but typically quite faster than)
any(item == A for item in B)