Empty List prints when trying to use a lambda mapping function on a filtered list

Question:

The problem I am working on requries the use of lambda mapping and filtering. The code should take the input array of arrays, filter out any negative values, and then square the remaining values. In the code below, the "print(list(my_list))" properly prints "[[1, 2, 6], [3, 4]]" but the "print(list(final))" returns an empty list rather than the expected sqared values of the previous print statement.

arr = [[-1, 1, 2, -2, 6], [3, 4, -5]]
def lambdaMap(arr):
    my_list = map(lambda x: list(filter(lambda y:y >= 0, x)), arr)
    print(list(my_list))
    final = list(map(lambda x: int(x)**2, list(my_list)))
    print(list(final))
  
lambdaMap(arr)

I have tried several iterations of the code block above, but the result was either a TypeError or an empty list on the final print statement rather than the desired output of [[1, 4, 36], [9, 16]]. Thank you for your time and help!

Asked By: DAS19

||

Answers:

@Fractalism already mentioned exhausting the generator, but this can be circumvented by simply not printing the intermediate output. However, there is another issue: your lambda is trying to square a list, which is not supported by the built-in list. You will need another lambda to square the list elements:

arr = [[-1, 1, 2, -2, 6], [3, 4, -5]]
def lambdaMap(arr):
    filtered = map(lambda x: list(filter(lambda y: y >= 0, x)), arr)
    final = map(lambda x: list(map(lambda y: y**2, x)), filtered)
    print(list(final))
  
lambdaMap(arr)

Output:

[[1, 4, 36], [9, 16]]
Answered By: B Remmelzwaal
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.