unexpected result when using a list comprehension on a list of booleans Python

  • A+
Category:Languages
r=[True, False,True,False, False] print([i for i in r if str(r[i])=="True"]) 

this code gives the following unexpected result: [False, False, False]

Why is this the behavior? I would expect: [True, True]


i is a boolean with a value of True or False. If you use it as an index in r[i], you will get either r[0] or r[1] because bool is a subclass of int.

You can picture it as r[int(i)] and int(True) == 1, int(False) == 0.

What you probably mean is:

print([i for i in range(len(r)) if str(r[i])=="True"]) 

where i is an integer or:

print([i for i in r if str(i)=="True"]) 

where i is a boolean.

Note that if i is a boolean, there is little point in if str(i) == "True". A more concise way of writing it would be:

print([i for i in r if i]) 

or even using the filter built-in function:

it = filter(None, r) print(list(it)) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: