开发者

What does it mean += in Python?

开发者 https://www.devze.com 2023-04-12 16:16 出处:网络
What does it mean when it\'s like this: self.something += (\'somethin\',) What does "+="开发者_JAVA百科 mean and what does the comma mean?The expression a += b is shorthand for a = a + b, w

What does it mean when it's like this:

self.something += ('somethin',)

What does "+="开发者_JAVA百科 mean and what does the comma mean?


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.


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号