Python Return Syntax Error

前端 未结 2 1373
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-22 02:02
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
         


        
2条回答
  •  渐次进展
    2021-01-22 02:47

    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.

提交回复
热议问题