relentlessruin
relentlessruin

Reputation: 81

Return true or false in a list comprehension 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?

Upvotes: 5

Views: 23493

Answers (4)

Faisal Sajeeb
Faisal Sajeeb

Reputation: 11

You can use list comprehension to get both boolean and values:

lst = [1,2,3,4]
result = [x%2 == 0 for x in lst] # Returns boolean
result_1 = [x for x in lst if x%2 == 0] # Returns values

Upvotes: 1

Anton Protopopov
Anton Protopopov

Reputation: 31662

You could also use bitwise & for that which is a bit faster then %:

t_f_list = [1,2,3,4]
res = [ not x&1 for x in t_f_list]
print(res)
[False, True, False, True]

Timing

In [72]: %timeit [not x&1 for x in t_f_list]
1000000 loops, best of 3: 795 ns per loop

In [73]: %timeit [ x % 2 == 0 for x in t_f_list]
1000000 loops, best of 3: 908 ns per loop

In [74]: %timeit list(map(lambda x: x%2 == 0, t_f_list))
1000000 loops, best of 3: 1.87 us per loop

Note: list for map is added to get a list of values because I'm using python 3.x

Upvotes: 2

Benjamin
Benjamin

Reputation: 3467

You can also use lambda instead :

l = [1,2,3,4]
map(lambda x: x%2 == 0, l)

Upvotes: 3

utdemir
utdemir

Reputation: 27216

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]

Upvotes: 16

Related Questions