0

why this python code

    a += 1

is better than

a = a + 1

other than the fact that first one is easier to understand and cleaner is there any other reason why i should use it like if there are any other difference how python deals with each statement or any performance difference between each or I could use whatever i want .

khaled
  • 69
  • 1
  • 7
  • Who says that one is better than the other? – Paul M. Apr 07 '20 at 23:23
  • Related question: [When is “i += x” different from “i = i + x” in Python?](https://stackoverflow.com/questions/15376509/when-is-i-x-different-from-i-i-x-in-python) – DarrylG Apr 07 '20 at 23:39

2 Answers2

1

In the simple case you give, there's little difference. Augmented assignment is just considered easier to read because it's a common idiom and expresses a common operation concisely.

But there are situations where it can make a difference. If the place you're incrementing comes from a complex expression or one that has side effects, you don't want to repeat it.

a[call_expensive_function()] += 1
vs
a[call_expensive_function()] = a[call_expensive_function()] + 1

Also, it's possible for a type to implement += differently from +. An example is lists:

l1 = [1, 2, 3]
l2 = l1
l1 = l1 + [4, 5]
print(l1) # prints [1, 2, 3, 4, 5]
print(l2) # prints [1, 2, 3]

l3 = [1, 2, 3]
l4 = l3
l3 += [4, 5]
print(l3) # prints [1, 2, 3, 4, 5]
print(l4) # prints [1, 2, 3, 4, 5]

Lists implement += by modifying the list in place (like the extend() method), while + creates a new list. As you can see from above, this has implications if you have multiple references to the same list.

user9985
  • 168
  • 15
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

a += 1 is little faster than a = a+1.

See the example code.

def f(a):
    while a < 10000:
        a += 1
    return a

def g(a):
    while a < 10000:
        a = a + 1
    return a

a = 1
%timeit f(a)
490 µs ± 20.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

a = 1
%timeit g(a)
513 µs ± 34.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Gilseung Ahn
  • 2,598
  • 1
  • 4
  • 11
  • Ok so what is the difference between each one .How each one works .where this difference came from – khaled Apr 08 '20 at 03:41