FW: Unexpexted behaviot of python operators on list

Mark Lawrence breamoreboy at yahoo.co.uk
Tue Nov 25 13:20:26 CET 2014


On 25/11/2014 11:40, Steven D'Aprano wrote:
> PANDEY2 Archana (MORPHO) wrote:
>
>> Hello
>>
>> I hereby would like to share the problem I have found regarding python
>> list implementation:-
>>
>> As per python documentation python list is mutable data object.
>>
>> That problem I found with the list is that is behaves differently when we
>> use '+=' and '+'  '=' operators separately. For example-
>> a=a+1 and a +=1  both behave in same way for all data types except python
>> list
>
> `a += b` is only *approximately* the same as `a = a+b`. The documentation
> says:
>
> An augmented assignment expression like x += 1 can be rewritten as x = x + 1
> to achieve a similar, but not exactly equal effect. In the augmented
> version, x is only evaluated once. Also, when possible, the actual
> operation is performed in-place, meaning that rather than creating a new
> object and assigning that to the target, the old object is modified
> instead.
>
> https://docs.python.org/2/reference/simple_stmts.html#augmented-assignment-statements
>
>
>> Please find the attached module and execute it on windows python32, See
>> the difference in output.
>
> I cannot see the attached module. Did you forget to attach it, or did your
> mail server delete it?
>

http://bugs.python.org/file37269/Operator_bug_python.py

a=[1,2,3]
b=a
b+=[4,5]
print(a)
print(b)

x=[1,2,3]
y=x
y=y+[4,5]
print(x)
print(y)

I know that you can explain it better than I can :)

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list