cerule
cerule

Reputation: 45

Python Return Syntax Error

def list_function(x):
    return x[1] += 3

I want to do this, but apparently I can't. I understand I can do this

x[1] += 3
return x

but, I wanted to keep it on a single line. Does return always need to be on its own line, and if not, why does it need to be in this particular case?

Upvotes: 2

Views: 560

Answers (2)

Sven Marnach
Sven Marnach

Reputation: 601599

You can have an arbitrary expression after the return statement, i.e. something that yields a value to be returned. Assignment, including augmented assignments like x[1] += 3, are not expressions in Python. They are statements, and as such don't yield a value, so they can't be used after return.

If you insist on having everything on a single line, you can of course write

x[1] += 3; return x

However, I can't see any valid reason to do so.

Upvotes: 2

Anand S Kumar
Anand S Kumar

Reputation: 90889

From documentation -

return_stmt ::= "return" [expression_list]

The return statement can only be followed by expressions. expression_list is -

expression_list ::= expression ( "," expression )* [","]

But x[1] += 1 is an augmented assignment statement , and as such you cannot have that after return .

Upvotes: 1

Related Questions