Suppose a = [[1,2,3],[1,2,3]]
reduce(lambda x,y: x==y, a)
returns True
But if a = [[1,2,3],[1,2,3],[1,2,3]]
reduce(lambda x,y: x==y, a)
returns False
Why in the second case, the outcome is False
?
please help
thanks
You can still use reduce! Check out this magic:
bool(reduce(lambda x,y: (x==y)*x, a))
Since the return value of the lambda for x==y
is True or False, that can be multiplied by the input and then used in the next comparison because True*[1,2,3]
is [1,2,3]
. It also works for strings, True*"MyString"
is "MyString"
.
Try it. However, this method will not work for a list of zeros.
Try this instead, it works for lists of any size:
all(e == a[0] for e in a)
Notice that your proposed solution using reduce
doesn't work for more than two items, as the accumulated value after the first comparison is True
, and you'd be comparing True
against each of the elements from that point on, and obviously that's not going to work.
You are not reducing the lists. The return value of your lambda is True
or False
, which is then used as input parameters to further calls to the same lambda function. So you end up comparing a boolean with a list. Therefore, the reducing function should return the same type as it input parameters.
You were probably looking for what other answers proposed instead: use all()
.
Because first time reduce compare [1,2,3] == [1, 2, 3] and it's true next time it compare True and [1,2,3] and it's false.
help(reduce)
Help on built-in function reduce in module __builtin__:
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With