One-line code?

In the control flow challenge the Same Name exercise (#2) has a pretty straight-forward solution:
def same_name(your_name, my_name):
if (your_name == my_name):
return True
return False

But apparently it’s possible to write this in one line of code? Any insights on that?

Think about what the condition equates to and compare it to what value is being returned.

return (your_name == my_name)

1 Like

Thank you, appreciate the help!

Two for you.

One of the main drivers behind Python is legibility, so it’s typically considered better (“more Pythonic”) to write functions which are more easily readable than to try and cram as much as possible into opaque one-liners.

That being said, you can create the entire function in one line of code using a Lambda function.

I’ve linked to the docs, so feel free to have a read and attempt it yourself…

Here’s an example.

same_name = lambda your_name, my_name: your_name == my_name

same_name("alan","bob") # False
same_name("alan","alan") # True

According to PEP 8 - Programming Recommendations, Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier:

# Correct:
def f(x): return 2*x

# Wrong:
f = lambda x: 2*x

The reason is because it is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression).

1 Like