'What does it mean += in Python?
What does it mean when it's like this:
self.something += ('somethin',)
What does "+=" mean and what does the comma mean?
Solution 1:[1]
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.
Solution 2:[2]
Python has an operator to assign value to a name and it's =
.
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 you're use to plus the =
sign.
For immutable objects (numbers, strings, tuples,...) you can't have in-place changes because... they're 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
Solution 3:[3]
+=
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.
Solution 4:[4]
results=[]
for x in range(5):
results += '$'
print(results)
output : ['$', '$', '$', '$', '$']
this code behaves differently from typical += operator , as you can see here it has generated list with $
sign inside it.
its is not like we think results = results+ '$'
this code will throw you an error.
What actually happens is += operator
works like .extend()
in lists.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | JBernardo |
Solution 3 | |
Solution 4 |