For what is += is used?

Hi
i am Aman
I am an beginner in python but I cannot understand what does this do(+=)?
Please help

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 :slight_smile:

1 Like

thanks for your help

Aside

+= 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.