TypeError when using ">=" in a lambda filter and trying to print in list form

Question:

I need to create a function that uses lambda filtering and mapping to go over an array of arrays and performs a calculation on them. The first step is to drop the negative numbers from each array. I was trying to set-up some general code using an example array of arrays:

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

When I run this I get a the following error "TypeError: ‘>=’ not supported between instances of ‘list’ and ‘int’"

When I changed it from ">=0" to "=0" it ran without an error, so it seems to be the ">" that is the issue. I tried printing without converting to a list and it just returned "<filter object at 0x00000202FDF5C4F0>" which is obviously unhelpful. Any suggestions would be greatly appreciated!

Asked By: DStepler19

||

Answers:

The issue with your code is that you are passing two arguments to the lambda function in the filter statement. The filter function takes a function and an iterable as arguments. The function should take one argument and return a boolean value. In your case, you want to filter out negative numbers from each array within the arr list of lists.

Here’s an example of how you can achieve this using lambda functions and the map function:

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

lambdaMap(arr)

This will output [[1, 2, 6], [3, 4]], which is a list of lists where each inner list has had its negative numbers removed.

I hope this helps! Let me know if you have any further questions.

Answered By: Peterrrrrrr
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.