Python Forum

Full Version: Simple code question about lambda and tuples
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a simple code:

my_tuple = (0,1,2,3,4,5,6)
foo = list(filter(lambda x: x-0, my_tuple))

print(foo)
I know what the output is and that it removes the first entry, the 0. I could also change it as follows:

my_tuple = (0,1,2,3,4,5,6)
foo = list(filter(lambda x: x-0 and x-1, my_tuple))

print(foo)
I thought that tuples are immutable? How are the 0 and 1 removed? How does this work and what is this x-0 actually doing?
foo is a list made by using my_tuple, if you print the tuple my_tuple you will find it has not changed.
Remember that 0 is treated as false when it is tested for its truth value (see the docs), so x - 0 will evaluate to True for any value that isn't 0. It's a strange way to write that predicate - it would be easier to read written as x != 0, obviously.
Or as x not in (0, 1)
(Oct-03-2021, 02:35 PM)ndc85430 Wrote: [ -> ]Remember that 0 is treated as false when it is tested for its truth value (see the docs), so x - 0 will evaluate to True for any value that isn't 0. It's a strange way to write that predicate - it would be easier to read written as x != 0, obviously.

Yes exactly != is what I would have expected. But ok, thanks for the answers!

So the point is:
it starts with x=0 and does the following:
0-0 and 0-1 which is: False and True => gives False
then it continues with the next element in the tuple, the 1:
1-0 and 1-1 which is: True and False => gives False
then 2:
2-0 and 1-1 which is: True and True => gives True

and so on, so that is why 0 and 1 are filtered out. Right?
(Oct-03-2021, 04:50 PM)JasPyt Wrote: [ -> ]2-0 and 1-1 which is: True and True => gives True
Output:
>>> 2-0 and 1-1 0
0 is False

but I guess you mean

Output:
>>> 2-0 and 2-1 1
(Oct-03-2021, 07:02 PM)buran Wrote: [ -> ]
(Oct-03-2021, 04:50 PM)JasPyt Wrote: [ -> ]2-0 and 1-1 which is: True and True => gives True
Output:
>>> 2-0 and 1-1 0
0 is False

but I guess you mean

Output:
>>> 2-0 and 2-1 1

Yes exactly!
The code is confusing if write like this will most will figure what's going with a quick look.
def number_remove(x: int) -> int:
    if x not in (0, 1):
        return x

my_tuple = (0,1,2,3,4,5,6)
print(list(filter(number_remove, my_tuple)))
Output:
[2, 3, 4, 5, 6]