0

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

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
Long Claw
  • 107
  • 2
  • 6

1 Answers1

4

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)
Cireo
  • 4,197
  • 1
  • 19
  • 24
  • Nice. It's probably more efficient then what I had in mind: ```[x for x in my_list if ("True" not in map(str, x))]``` – shcrela Jan 02 '21 at 22:17
  • 1
    Yeah, you avoid str-casting, false positive for "True" or objects that have a str/repr of "True", and in py27 an unnecessary list construction =) – Cireo Jan 02 '21 at 22:31