0

I can't understand the explanation about evaluations.

What is the difference between normal and augmented assignments about this?

I know about in-place behavior.

https://docs.python.org/3/reference/simple_stmts.html#grammar-token-augmented-assignment-stmt

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

interjay
  • 107,303
  • 21
  • 270
  • 254
peppaa
  • 111
  • 1
  • 2
    Read https://www.python.org/dev/peps/pep-0203/ for a better explanation: _... also a way for the left-hand operand in question to know that it should operate on itself, rather than creating a modified copy of itself_. – Adrian W Apr 03 '21 at 09:04
  • @AdrianW What you quoted is the difference about mutating in-place, not the difference in evaluating only once. – interjay Apr 03 '21 at 09:24

1 Answers1

4

For a simple variable x, there is nothing to evaluate. The difference is seen when x is an expression. For example:

some_list[get_index()] = some_list[get_index()] + 1
some_list[get_index()] += 1

The first line will call get_index() twice, but the second one calls it once.

The second difference mentioned is when x is a mutable object like a list. In that case x can be mutated in place instead of creating a new object. So for example lst = lst + [1,2] has to copy the entire list to the new one, but lst += [1,2] will mutate the list itself which might be possible to do without having to copy it. It also affects whether other references to lst see the change:

lst = [1,2,3]
lst2 = lst
lst += [4]         # Also affects lst2
lst = lst + [5]    # lst2 is unchanged because lst is now a new object
interjay
  • 107,303
  • 21
  • 270
  • 254