3

I made a list comprehension to only add numbers less than or equal to 5 to b, but when I run my program it outputs Boolean's instead of integers.

How do I change them to integers.

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [i <= 5 for i in a]
print b

[True, True, True, True, True, False, False, False, False, False, False]
Allen Birmingham
  • 150
  • 1
  • 1
  • 10
  • You are asking python to check whether or not each entry in a is less than or equal to 5. So python is populating b with the answer. Check out Keiwan's answer for the correct way to accomplish your code. – Will.Evo Jul 12 '16 at 20:37

1 Answers1

8

This is the correct way to achieve what you want:

b = [i for i in a if i <= 5]

Your version is putting the result of the expression i <= 5 - which is a boolean - into the list for every element in a, no matter what the outcome of the comparison is.

Keiwan
  • 8,031
  • 5
  • 36
  • 49