What does += mean in Python?
Solution 1:
a += b
is essentially the same as a = a + b
, except that:
-
+
always returns a newly allocated object, but+=
should (but doesn't have to) modify the object in-place if it's mutable (e.g.list
ordict
, butint
andstr
are immutable). -
In
a = a + b
,a
is evaluated twice. -
Python: Simple Statements
- A simple statement is comprised within a single logical line.
If this is the first time you encounter the +=
operator, you may wonder why it matters that it may modify the object in-place instead of building a new one. Here is an example:
# two variables referring to the same list
>>> list1 = []
>>> list2 = list1
# += modifies the object pointed to by list1 and list2
>>> list1 += [0]
>>> list1, list2
([0], [0])
# + creates a new, independent object
>>> list1 = []
>>> list2 = list1
>>> list1 = list1 + [0]
>>> list1, list2
([0], [])
Solution 2:
a += b
is in this case the same as
a = a + b
In this case cnt += 1 means that cnt is increased by one.
Note that the code you pasted will loop indefinitely if cnt > 0 and len(aStr) > 1.
Edit: quote Carl Meyer: ``[..] the answer is misleadingly mostly correct. There is a subtle but very significant difference between + and +=, see Bastien's answer.''.
Solution 3:
Google 'python += operator' leads you to http://docs.python.org/library/operator.html
Search for += once the page loads up for a more detailed answer.
Solution 4:
FYI: it looks like you might have an infinite loop in your example...
if cnt > 0 and len(aStr) > 1:
while cnt > 0:
aStr = aStr[1:]+aStr[0]
cnt += 1
- a condition of entering the loop is that
cnt
is greater than 0 - the loop continues to run as long as
cnt
is greater than 0 - each iteration of the loop increments
cnt
by 1
The net result is that cnt
will always be greater than 0 and the loop will never exit.