I am trying to make an if statement inside a lambda but the catch is I also trying to make all odd numbers to the third too, the lambda line is ignoring the i**3,


numbers = range(1,10)

odd_numbers_to_the_third_2 = list(filter(lambda i : i**3 if i%2!=0 else None , numbers))

in the second line of the code I am trying to i**3 if its an odd number but the result shows the odd numbers without making it **3 I get [1,3,5,7,9] instead of [1,27,125,343,729]

5 Answers

1
mohammad RaoofNia On Best Solutions

as filter() just checks the list items and returns the values which satisfies the condition, you can use map() to do what you want:

  1. this code:
odd_numbers_to_the_third_2 = list(map(lambda i : i**3 if i%2!=0 else None , numbers))

with this output:

[1, None, 27, None, 125, None, 343, None, 729]
  1. or this one:
odd_numbers_to_the_third_2 = list(map(lambda i : i**3 if i%2!=0 else None , list(filter(lambda i : i%2!=0, numbers ))))

for this output:

[1, 27, 125, 343, 729]
0
Netwave On

You can use a comprehension:

>>> odd_numbers_to_the_third_2 = [i**3 for i in numbers if i%2 != 0]
>>> odd_numbers_to_the_third_2
[1, 27, 125, 343, 729]

Using filter and map:

>>> odd_numbers_to_the_third_2 = list(map(lambda x: x**3, filter(lambda x: x%2 != 0, numbers)))
>>> odd_numbers_to_the_third_2
[1, 27, 125, 343, 729]
0
ghr On

Use map to get the number cubed, then filter out None values:

odd_numbers_to_the_third_2 = list(filter(bool,map(lambda i : i**3 if i%2!=0 else None, numbers)))

Or, use a generator expression to only apply map to odd numbers and discard the rest:

odd_numbers_to_the_third_2 = list(map(lambda i : i**3, (num for num in numbers if num%2!=0)))

Or don't use map/filter at all:

odd_numbers_to_the_third_2 = [num**3 for num in numbers if num%2 != 0]

All approaches output:

[1, 27, 125, 343, 729]
0
PyPingu On

As mentioned in a comment filter doesn't perform any actual transformation, it just uses your lambda to decide what to return.

Instead I would use a list comprehension with conditional:

numbers = range(1,10)
odd_numbers_to_the_third_2 = [i**3 for i in numbers if i%2 != 0]
0
Austin On

filter() filters and does not transform list. map() is for transformation.

So, you should filter first to get all odd numbers and map to transform:

list(map(lambda x: x ** 3, filter(lambda i: i % 2, numbers)))

Ideally, you should use list-comprehension which is proven effective than map/filter lambda combinations:

[x ** 3 for x in numbers if x % 2]