[Tutor] could someone explain why this happens to me.
Emad Nawfal (عماد نوفل)
emadnawfal at gmail.com
Sat Mar 7 20:28:35 CET 2009
On Sat, Mar 7, 2009 at 2:09 PM, sphennings W. <sphennings at gmail.com> wrote:
> When I enter the following code into IDLE do both lists have the same
> value?
> How would I manipulate both lists separately?
>
> >>> List1=[1,2,3]
> >>> List2=List1
> >>> List2.reverse()
> >>> print(List2)
> [3, 2, 1]
> >>> print(List1)
> [3, 2, 1]
> >>> List2.append(0)
> >>> print(List2)
> [3, 2, 1, 0]
> >>> print(List1)
> [3, 2, 1, 0]
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
When you assign list2 to list1, you are just referencing the old list.
Whatever you do either one, it will affect the other as well. The solution,
to my limited knowledge, is to deep-copy the list, as illustrated here:
>>> l1 = [1,2,3]
>>> import copy
>>> l2 = copy.deepcopy(l1)
>>> l2
[1, 2, 3]
>>> l1.reverse()
>>> l1
[3, 2, 1]
>>> l2
[1, 2, 3]
>>>
--
لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.....محمد
الغزالي
"No victim has ever been more repressed and alienated than the truth"
Emad Soliman Nawfal
Indiana University, Bloomington
http://emnawfal.googlepages.com
--------------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090307/5a7c2ff2/attachment-0001.htm>
More information about the Tutor
mailing list