syntax – What does it mean += in Python?

syntax – What does it mean += in Python?

The expression a += b is shorthand for a = a + b, where a and b can be numbers, or strings, or tuples, or lists (but both must be of the same type).

The comma in (x,) means that this is a tuple of a single element, x . If the comma is absent, is just an x between parenthesis.

Python has an operator to assign value to a name and its =.

The language also support many other operators like +, -, ** for operations defined in special methods of your objects.

Although + is the math sign to add things, it can be customized to do whatever you want.

Sometimes you want to make an operation and store it using the same name. For these situations you have in-place operators that are just the normal operators youre use to plus the = sign.

For immutable objects (numbers, strings, tuples,…) you cant have in-place changes because… theyre immutable. So, the in-place methods do exactly the same thing the normal method followed by an assignment.

For mutable objects the difference is much clear:

In-place add:

>>> a = []
>>> b = a
>>> b += [1,2]
>>> a
[1, 2]

Add and assign:

>>> a = []
>>> b = a
>>> b = b + [1,2]
>>> a

See? The object itself was transformed with the in-place add for lists, but, on the other case, a new object was created.

For your other question, the comma is the tuple separator.

a = (1)   # Just number 1 inside parenthesis
a = (1,)  # A tuple with one element

syntax – What does it mean += in Python?

+= is addition and assignment into one (sometimes referred to as iadd or in-place add). It is the same as a = a + x

a = 4
a += 5  # add 5 to a, and assign the result into a
b = 4
b = b + 5   # this does the same thing as +=
print a  # prints out 9
print b  # prints out 9

You can also do other operations in this style, such as -=, *=, /=, &= (bitwise and), |= (bitwise or), ^= (bitwise xor), %= (mod), **= (exponent).

(something,) is a tuple. (something) (without the comma) is using the parenthesis in grouping, kind of like (some + thing) or (a + b). In order to differentiate between the one-member tuple and the grouping syntactically, Python uses a comma.

Leave a Reply

Your email address will not be published.