Search code examples
pythonpython-3.xlambda

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


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))```

Solution

  • 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)))