tags:

views:

2038

answers:

7

I see code like this for example in Python:

    if cnt > 0 and len(aStr) > 1:
        while cnt > 0:                  
            aStr = aStr[1:]+aStr[0]
            cnt += 1

What does the += mean?

+22  A: 
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.''.

Stephan202
@Stephan202 += 1
STW
thanks a lot! i never knew that. i always saw this but i never quite knew
It works for other operators too. You can do x -= 1; y *= 3; z /= 10;cnt += 1; could be considered neater than cnt = cnt + 1; where there is more room for a typo ;)
joeytwiddle
'Is the same as' isn't quite correct. See Bastien's answer
James Hopkin
-1: No link to the documentation.
S.Lott
@S.Lott: A downvote means an answer is NOT helpful, which this one is. You downvoted it just because he didn't link to the docs?
Graeme Perrow
-1 because the answer is misleadingly mostly correct. There is a subtle but very significant difference between + and +=, see Bastien's answer.
Carl Meyer
@Carl: edited the answer to emphasise your remark. Thanks!
Stephan202
A: 

it means "append "THIS" to the current value"

example:

a = "hello"; a += " world";

printing a now will output: "hello world"

VeeBee
no, it doesn't mean append
hasen j
Please, for the love of Satan, do not use this for building strings. StringIO and cStringIO are here for this purpose.
RommeDeSerieux
building strings: "".join( ITERABLE_OF_STRINGS ) also performs well.
bendin
It means append when used on strings.. "".join() is better performing, but it's stupid to use that for a short strings like in the example. You use "".join() when concat'ing strings in a loop, but for one-of uses, += is fine
dbr
+1  A: 

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.

STW
Not necessarily forever - if cnt is an int, it will eventually overflow and go negative, so the loop will finally exit after a couple billion iterations if you're on a machine with 32-bit ints (or sometime around the heat death of the universe if you're on a machine with 64-bit ints.)
Charlie Tangora
@Charlie: Python handles overflowing automatically. Tested with Python 2.5: sys.maxint + 1 == 2147483648L and isinstance(sys.maxint + 1, int) == False. As of Python 3.0 the distinction between int and long is even gone (no more long, int is a 'bignum').
Stephan202
(Obviously on 64bit we have sys.maxint + 1 == 9223372036854775808L, but the point is that the result is automatically converted to long)
Stephan202
+7  A: 

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.

Gishu
or you could just tell him it means a = a + b
hasen j
and have him come back for 'what is -=?' 'what is *=?' :) no thanks. Anyways the top voted ans already did that before I posted.
Gishu
+1: Link to the documentation.
S.Lott
+1 for providing the link (helpful), but -1 for not summarizing, which you could have done in one sentence. Net: 0
Graeme Perrow
+41  A: 

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 or dict, but int and str are immutable).
  • In a = a + b, a is evaluated twice.

http://docs.python.org/reference/simple_stmts.html#augmented-assignment-statements


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], [])
Bastien Léonard
+1 for the distinction between the two forms when used with mutable objects
James Hopkin
Minor correction: the in-place modification occurs if the object supports __iadd__() method, not if it's mutable. In particular, dictionaries don't support `+=`.
Rafał Dowgird
@Rafal: clearly if an object doesn't support +=, in-place modification won't occur :-) The subtle point is there's no guarantee that a mutable object supporting += will do in-place modification - careful code will avoid relying on this, except where it's explicitly documented.
James Hopkin
@Rafal: I edited to make it more clear.
Bastien Léonard
Added an example.
Bastien Léonard
+1  A: 

+= is the in-place addition operator.

It's the same as doing cnt = cnt + 1. For example:

>>> cnt = 0
>>> cnt += 2
>>> print cnt
2
>>> cnt += 42
>>> print cnt
44

The operator is often used in a similar fashion to the ++ operator in C-ish languages, to increment a variable by one in a loop (i += 1)

There are similar operator for subtraction/multiplication/division/power and others:

i -= 1 # same as i = i - 1
i *= 2 # i = i * 2
i /= 3 # i = i / 3
i **= 4 # i = i ** 4

The += operator also works on strings, for example:

>>> s = "Hi"
>>> s += " there"
>>> print s
Hi there

People tend to recommend against doing this for performance reason, but for the most scripts this really isn't an issue. To quote from the "Sequence Types" docs:

  1. If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.

The str.join() method refers to doing the following:

mysentence = []
for x in range(100):
    mysentence.append("test")
" ".join(mysentence)

..instead of the more obvious:

mysentence = ""
for x in range(100):
    mysentence += " test"

The problem with the later is (aside from the leading-space), depending on the Python implementation, the Python interpreter will have to make a new copy of the string in memory every time you append (because strings are immutable), which will get progressively slower the longer the string to append is.. Whereas appending to a list then joining it together into a string is a consistent speed (regardless of implementation)

If you're doing basic string manipulation, don't worry about it. If you see a loop which is basically just appending to a string, consider constructing an array, then "".join()'ing it.

dbr