"+=" does not work correct all alogn

Arnaud Delobelle arnodel at gmail.com
Wed Jan 18 12:09:55 EST 2012


On 18 January 2012 09:52, Wilfried Falk <w_h_falk at yahoo.de> wrote:
> Hello Pythons,
>
> attached to this email is a pdf-file which shows, that  "+=" does not work
> well all along. Mybe somebody of you is able to explain my observations in
> this respect. I will be glad about an answer.

I think you are more likely to get answers if you post your code in
the body of your message rather than attach it in a pdf, which is
quite an unusual thing to do!

"""
1.) For   identifier += 1   you sometimes get    print(); identifier =
identifier + 1
What means that there is a prior  print().  I could not find out a
rule for when this happens --- but it
does. By replaceing  identifier += 1   with   identifier = identifier
+ 1    the malfunction (print()) allways
disappears
"""

I can't comment on this as you don't provide any code.

"""
2.)  Another  "mystery"  is shown by the code below. There   _list +=
[something]    is not the same
as   _list = _list + [something].
def conc1(a, _list = []):
    _list = _list + [a]
    return _list
def conc2(a, _list = []):
    _list += [a]
    return _list
# Main Program
for i in range(4):
    _list = conc1(i)
    print(_list)
print()
for i in range(4):
    _list = conc2(i)
    print(_list)
In the first case the result of   print(_list)   is:
[0]
[1]
[2]
[3]
In the second case the result of   print(_list)   is:
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
"""

This behaviour is not a bug, it is a consequence of two things:

1. The way mutable default arguments work in Python.  Your
misunderstanding is a very common one for Python beginners.  There's a
good explanation of the behaviour here:

    http://effbot.org/zone/default-values.htm

2. The difference between

    lst += [a]

and

    lst = lst + [a]

The first one mutates the list object named 'lst' by appending 'a' at
its end, whereas the second one creates a new list made of the items
of lst with 'a' appended at the end.  So your function conc1 does not
mutate _list, whereas your function conc2 does.

HTH

-- 
Arnaud



More information about the Python-list mailing list