Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Functional Python The Lambda Lambada Lambda

Laurens Sandt
Laurens Sandt
3,513 Points

reduce and lambda doesn't pass challenge, but does result in the longest string in PyCharm

longest = reduce(lambda a, b: a if len(a) > len(b) else b, [x for x in strings])

doesn't pass in the challenge

running this in PyCharm print(longest) results in My grandmother started walking five miles a day when she was sixty. She's ninety-seven know and we don't know where she is. which is the longest sentence such a bummer

Laurens Sandt
Laurens Sandt
3,513 Points

As the question to what the return value should be is ambiguous, either the string itself or the length of the longest string. You can use the following alternative:

alternative = reduce(lambda a, b: a if a > b else b, [len(x) for x in strings])

which results in 123

btw it keeps asking me if I used reduced and lambda

yes I did :)

2 Answers

One of the beauties of functional programming is list comprehension is something that is rarely needed. the comprehension is already iterating over strings so there isn't a need for a list comprehension here.

Also the output it is expecting is a string, not an integer.

longest = reduce(lambda x,y: x if len(x) > len(y) else y, strings)