(a==b) ? 'Yes' : 'No'

Lie Ryan lie.1296 at gmail.com
Tue Apr 6 18:50:30 CEST 2010


On 04/07/10 00:16, Albert van der Horst wrote:
> In article <houv8a$ed9$02$2 at news.t-online.com>,
> Peter Otten  <__peter__ at web.de> wrote:
>> Pierre Quentel wrote:
>>
>>> I'm surprised nobody proposed a solution with itertools ;-)
>>
>> next(itertools.takewhile(lambda _: a == b, ["yes"]), "no")
> 
> I could learn something here, if you explain it?

The signature for next() is:
next(iterator[, default])

In particular, pay attention the `default` parameter.

next() returns `default` if StopIteration is raised else it returns
iterator.__next__().

takewhile(predicate, ["yes"]).__next__() return the string "yes" if
predicate("yes") returns True else it raises StopIteration.

The predicate (lambda _: a == b) returns True if (a == b) is True
otherwise it returns False.

Put the next(), takewhile(), and the predicate together and you get an a
monster that returns `default` if a == b is False else "yes".



More information about the Python-list mailing list