For example, if I wanted to know what numbers are divisible by 2 and had
test_list = [6, 4, 8, 9, 10]
print([number % 2 == 0 for number in test_list])
which would evaluate to:
[True, True, True, False, True]
What can I do to get the elements that evaluate to True in a list? Like this:
[6, 4, 8, 10]
(in python)
Ok, you where very close to the solution. In your list comprehension you told the program to put in the list not number
, the actual member of your list, but number % 2 == 0
, that is of course a bool
type.
To get the list you want, you have to tell the comprehension to get number
from test_list
each time the condition you want is met (in your case that it's even)
print([number for number in test_list if number % 2 == 0])