Find odd numbers in a list and square them using lambda function

Question:

Here is the code I have got so far. Now output is [1, 3, 5, 7, 9]

N = 10
for i in range(1, 10):
    arr.append(i)

arr2 = []
f = lambda x: x ** 2
arr2 = filter(lambda x: x % 2 != 0, arr)
map(lambda x: x ** 2, arr2)
print(list(arr2))```
Asked By: Elgernon

||

Answers:

Here’s a very slightly modified version:

arr = []
N = 10
for i in range(1, N):
    arr.append(i)

arr2 = []
f = lambda x: x ** 2
arr2 = filter(lambda x: x % 2 != 0, arr)
for i in list(arr2):
    print(f(i))

arr2 isn’t a list. It’s an iterator, which you can only convert to a list once.

Here’s a more compact version:

N = 10
arr = range(1, N)

square = lambda x: x ** 2
keep_odd = lambda x: x % 2 != 0
arr2 = list(filter(keep_odd, arr))
for i in arr2:
    print(square(i))

print(arr2)

It outputs:

1
9
25
49
81
[1, 3, 5, 7, 9]
Answered By: Eric Duminil

You are discarding the result of f(i) as soon as you create it. You need to append it to some list (also, no need to consume the filter object into a list):

result = []
for i in arr2:
    result.append(f(i))

Please note that binding a lambda to an identifier is discouraged in accordance with PEP 8.

The best way to solve this problem is without list comprehensions is a combination of filter and map like so:

arr2 = list(map(lambda x: x ** 2, filter(lambda x: x % 2 != 0, arr)))
Answered By: iz_

You aren’t saving the value in the array, you are just printing it.

N = 10
for i in range(1, 10):
    arr.append(i)

result = []
f = lambda x: x ** 2
arr2 = filter(lambda x: x % 2 != 0, arr)
for i in arr2:
    result.append(f(i))    
print(result)
Answered By: Jonathan Porter

Your last for-loop applies the lambda function to the elements in your list, but does not save the result.
Try:

a = [i for i in range(1,10)]
a2 = filter(lambda x: x % 2 != 0, a)
a3 = map(lambda x: x**2, a2)        # This is a generator object
final_list = list(a3)               # This is a list

Python Tips on map filter reduce

Answered By: Kelym
lst = [1, 2, 3]

ans = list(map(lambda x: x ** 2, filter(lambda x: x % 2 != 0, lst)))

print(ans)
Answered By: Rakesh Kumar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.