0

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?

2
  • 2
    If it helps, that's equivalent to foo = [x for x in my_tuple if (x - 0 and x - 1)]...
    – AKX
    Commented Jul 8 at 10:16
  • That's lambda x: followed by the lambda body x-0 and x-1 which checks if x-0 and x-1 are both non-zero.
    – tripleee
    Commented Jul 8 at 10:18

2 Answers 2

1
  1. 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).
  2. In simple word this will filter the list where ever x is either 0 or 1

So output will be [2, 3, 4, 5]

0

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
  • Applying 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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.