FW: Unexpexted behaviot of python operators on list

Dave Angel davea at davea.name
Tue Nov 25 07:25:49 EST 2014


On 11/25/2014 04:23 AM, PANDEY2 Archana (MORPHO) wrote:
> Hello
>

Welcome.  This is apparently your first post, or at least first for 
quite a while.

Note that this is a text forum (usenet, mailing list), and doesn't 
properly support either html messages nor attachments.  Just tell your 
mailer to use text, and paste your problem code into your message 
instead of trying to attach it.

> 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
>
> Please find the attached module and execute it on windows python32, See the difference in output.
>

I'm going to guess what your problem is, without seeing your module.

list1 = list2 = [1, 3, 5]
list1 += [7]
print(list1, list2)

#The += operator will affect list 2, not just list1.

list1 = list2 = [1, 3, 5]
list1 = list1 + [7]
print(list1, list2)

#The + operator makes a new object, and binds it to list1, leaving
#   list2 unchanged.

This is exactly according to spec, and will work the same for any 
mutable type.  For immutable types, the first behavior cannot happen, so 
it changes to the second.

It's certainly possible some other mutable types will behave 
differently, as each object type can implement its own behavior, based 
on its special methods.

No time right now to test this, so apologies if I have typos.





-- 
DaveA



More information about the Python-list mailing list