Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return true or false in a list comprehension python

Tags:

python

The goal is to write a function that takes in a list and returns whether the numbers in the list are even resulting in True or False. Ex. [1, 2, 3, 4] ---> [False, True, False, True]

I've written this portion of code:

def even_or_odd(t_f_list):
   return = [ x for x in t_f_list if x % 2 == 0]

I know this code would return [2, 4]. How would I make it so it instead returns a true and false like the above example?

like image 916
relentlessruin Avatar asked Feb 04 '16 10:02

relentlessruin


2 Answers

Instead of filtering by predicate, you should map it:

def even_or_odd(t_f_list):
   return [ x % 2 == 0 for x in t_f_list]
like image 156
utdemir Avatar answered Sep 21 '22 07:09

utdemir


You can also use lambda instead :

l = [1,2,3,4]
map(lambda x: x%2 == 0, l)
like image 28
Benjamin Avatar answered Sep 23 '22 07:09

Benjamin