i am Aman
I am an beginner in python but I cannot understand what does this do(+=)?
Hey, welcome to the forums!
+= means to increase a variable by a particular amount, for example:
a = 0 a += 5 print(a) # 5
Is identical to:
a = 0 a = a + 5 print(a) # 5
It’s just a shorter way of writing it
thanks for your help
+= is going to come up in a number of situations, the above example notwithstanding. We must look a little deeper into the genus of this syntax. In other words, we shant pass it off as a shortcut.
a = a + 1
is a reassignment.
a += 1
is an in-place operation.
The first requires very little in terms of processing but the latter is obviously using some built in machinery to complete its task. In other words, not a short cut. They are worlds apart.
There are several objects that support this operator. Can you find more instances?
+= is a shortcut, but for
list.extend(), not for incrementing
a. The reassignment approach is more efficient, in real terms. This fancy syntax has no value in that respect. For extending a sequence it is provably useful.
This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.