What does the expression do?
my_tuple = (0, 1, 2, 3, 4, 5)
foo = list(filter(lambda x: x-0 and x-1, my_tuple))
print(foo)
What output is to be expected from above equation?
New contributor
user26230692 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
lambda
is a quick way to create a one liner function, where the left side of the :
is the function’s argument and the right side is the returned value.
Let’s break this expression down, working from the inside out:
lambda x:x-0 and x-1
is a function that takesx
, calculatesx-0
(which is justx
),x-1
and performs a logical “and” operation between them. This function will returnTrue
if both sides of theand
are not zero. In other words, it will returnTrue
ifx
is neither0
nor1
.filter(lambda x:x-0 and x-1, my_tuple)
takesmy_tuple
, and evaluates every element with the function defined above, keeping only those that returnTrue
- Applying
list
to the result of thefilter
call converts the resultingfilter
object to a list.
So, to summarize – this call retuns a list
containing all the elements in my_tuple
that aren’t 0
or 1
.