2

Suppose I have function with list parameter, and inside it's body I want to modify passed list, by this code:

spy = [0,0,7]

def replace_spy(lista):
    return lista[2]=lista[2]+1

but it show me the error : SyntaxError: invalid syntax

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
  • See also: [Assignment inside lambda expression in Python - Stack Overflow](https://stackoverflow.com/questions/6282042/assignment-inside-lambda-expression-in-python) – user202729 Aug 15 '21 at 00:49

1 Answers1

5

Assignment is a statement, not an expression. It has no value. So you can't return the value of an assignment.

Across languages that do allow this kind of thing, it's ambiguous what exactly the return value should be, but most of them—including C and the many languages derived from or inspired by C—would give you the new value of lista[2]1. So presumably you want this:

def replace_spy(lista):
    lista[2]=lista[2]+1
    return lista[2]

If you're looking to shorten things, this is fewer keystrokes, and probably more readable:

def replace_spy(lista):
    lista[2] += 1
    return lista[2]

1. As an "lvalue", but that isn't a meaningful thing in Python.

cs95
  • 379,657
  • 97
  • 704
  • 746
abarnert
  • 354,177
  • 51
  • 601
  • 671
  • 2
    To shorten keystrokes even more, OP needs to get rid of the function entirely and just do `lista[2] += 1` :D – cs95 May 05 '18 at 22:38
  • @cᴏʟᴅsᴘᴇᴇᴅ Well, yeah, but let's assume this is a MCVE for a slightly less trivial function… – abarnert May 05 '18 at 22:39