2
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?

3
  • 3
    The problem is not the return, but rather that x[1] += 3 is not an expression, it's a complete statement and thus belongs to its own line Commented Sep 3, 2015 at 19:20
  • Ah, that was my suspicion, but I was hoping something like this could get around that return (x[1] += 3). Thanks for the help! Commented Sep 3, 2015 at 19:29
  • 2
    As a side note, return x[1] += 3; is valid C code, but it's equivalent to x[1] += 3; return x[1];. Commented Sep 3, 2015 at 19:42

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, thank you. I agree with you on the last part. That's technically one line, but not what I meant and I believe you understood that.
1

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 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.