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?
x-0 and x-1
→ can be change x and x-1
, it will check if x
is not 0 or x-1
is not 0, (0 stands for False and any other number is stand for True in Python).So output will be [2, 3, 4, 5]
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 takes x
, calculates x-0
(which is just x
), x-1
and performs a logical "and" operation between them. This function will return True
if both sides of the and
are not zero. In other words, it will return True
if x
is neither 0
nor 1
.filter(lambda x:x-0 and x-1, my_tuple)
takes my_tuple
, and evaluates every element with the function defined above, keeping only those that return True
list
to the result of the filter
call converts the resulting filter
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
.
foo = [x for x in my_tuple if (x - 0 and x - 1)]
...lambda x:
followed by the lambda bodyx-0 and x-1
which checks ifx-0
andx-1
are both non-zero.