Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a list of tuples with lambda expressions in Python

Tags:

python

lambda

What would be the right filter so l will contain [(7,10),(9,20)]

>>> l=[(0,5),(7,10),(9,20),(18,22)]
>>> l=filter(lambda x: x[0]>6 and x[1]<21, l)
>>> l
<filter object at 0x7fb2349829e8>
>>> 

I'm getting a "filter object", rather than a list of the 2 middle tuples from the original list.

like image 457
Beverly Williams Avatar asked Jul 13 '16 20:07

Beverly Williams


People also ask

How do you filter a list using lambda expression in Python?

We can use Lambda function inside the filter() built-in function to find all the numbers divisible by 13 in the list. In Python, anonymous function means that a function is without a name. The filter() function in Python takes in a function and a list as arguments.

How do you filter a list of tuples in Python?

To filter items of a Tuple in Python, call filter() builtin function and pass the filtering function and tuple as arguments. The filtering function should take an argument and return True if the item has to be in the result, or False if the item has to be not in the result.

What is lambda and filter in Python?

Syntax. Lambda arguments: expression. Return value: The value computed by substituting arguments in the expressions. Lambda expressions are often abbreviated by the name of anonymous functions as they are not given any name. Here no def keyword dis required for the declaration of function.

How do you sort a list with lambda?

Use the list sort() method to sort a list with a lambda expression in Python. Just call the list. sort(key=None) with a key set to a lambda expression to sort the elements of the list by the key.


1 Answers

>>> l=[(0,5),(7,10),(9,20),(18,22)]
>>> l=filter(lambda x: x[0]>6 and x[1]<21, l)
>>> list(l)
>>> [(7,10),(9,20)]
like image 192
niklas Avatar answered Nov 14 '22 22:11

niklas