0
list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
[i for i in list1 if i]

['Mike', 'Emma', 'Kelly', 'Brad']

Why is it that simply saying "if i" works?

Why doesn't i==True work? Or why doesn't i==False return anything?

I ask because the following code returns a list of booleans:

for i in list1:
    print (i != "")


True
False
True
True
False
True

Thank you,
R user

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Antonio
  • 417
  • 2
  • 8
  • 1
    Because **none of the items in the list `== True`. Or `False` for that matter, since they are all strings, and no string is ever equal to a bool – juanpa.arrivillaga Dec 22 '22 at 02:52

1 Answers1

0

This is because i is a string and True or False is are boolean values.

When you do if i it checks wether i is an empty string and if not it returns True.

But when you check if i == True it checks whether the value of i is a boolean value and whether its True. In your case it will always resolve to False since i is a string and does not hold a boolean value.

  • 1
    It's a bit more complicated that. Simple example: `1 == True` returns `True`. – Axe319 Dec 22 '22 at 03:05
  • But that's because in Python3 boolean type is a subtype of integer type and the boolean values `False` and `True` are mapped to 0 and 1 respectively. https://docs.python.org/3/reference/datamodel.html#index-10 – Prateek Singh Dec 22 '22 at 05:06