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.
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.
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.
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.
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.
>>> 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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With