The output only one number in if statment

45 Views Asked by At

It is a beginner's question, how come the output is only number 1 in this code. is it supposed to be all numbers?

a = [1, 2, 3, []]
for number in a :
   if number == True:
      print(number)

I expected to be:

1
2
3 

but it only get:

1
1

There are 1 best solutions below

1
user2390182 On

Just use

if number:

That will cover all non-zero numbers (and other objects) as they are "truthy" as in bool(number) == True.

If you compare number == True, you only get 1 since 1 == True but not 2 == True.

Note that bool is a subclass of int with 0 == False and 1 == True.