user3300676 - 9 months ago 60

Python Question

My understanding about filtering lists with lambda is that the filter will return all the elements of the list that return True for the lambda function. In that case, for the following code,

`inputlist = []`

inputlist.append(["1", "2", "3", "a"])

inputlist.append(["4", "5", "6", "b"])

inputlist.append(["1", "2", "4", "c"])

inputlist.append(["4", "5", "7", "d"])

outputlist = filter(lambda x: (x[0] != "1" and x[1] != "2" and x[2] != "3"), inputlist)

for item in outputlist: print(item)

The output should be

`['4', '5', '6', 'b']`

['1', '2', '4', 'c']

['4', '5', '7', 'd']

But the output that I get is

`['4', '5', '6', 'b']`

['4', '5', '7', 'd']

I get the expected output, if I use

`outputlist = filter(lambda x: (x[0] != "1" or x[1] != "2" or x[2] != "3"), inputlist)`

What am I doing silly here? Or is my understanding not correct?

Answer

`x = ['1', '2', '4', 'c']`

, so `x[1]=='2'`

, which makes the expression `(x[0] != "1" and x[1] != "2" and x[2] != "3")`

be evaluated as `False`

.

When conditions are joined by `and`

, they return `True`

only if all conditions are `True`

, and if they are joined by `or`

, they return `True`

when the first among them is evaluated to be `True`

.