Simple code question about lambda and tuples - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Simple code question about lambda and tuples (/thread-35144.html) |
Simple code question about lambda and tuples - JasPyt - Oct-03-2021 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? RE: Simple code question about lambda and tuples - Yoriz - Oct-03-2021 foo is a list made by using my_tuple , if you print the tuple my_tuple you will find it has not changed.
RE: Simple code question about lambda and tuples - ndc85430 - Oct-03-2021 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.
RE: Simple code question about lambda and tuples - deanhystad - Oct-03-2021 Or as x not in (0, 1) RE: Simple code question about lambda and tuples - JasPyt - Oct-03-2021 (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 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? RE: Simple code question about lambda and tuples - buran - Oct-03-2021 (Oct-03-2021, 04:50 PM)JasPyt Wrote: 2-0 and 1-1 which is: True and True => gives True 0 is Falsebut I guess you mean
RE: Simple code question about lambda and tuples - JasPyt - Oct-04-2021 (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 True0 is False Yes exactly! RE: Simple code question about lambda and tuples - snippsat - Oct-04-2021 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)))
|