Newbie-list-problem: how to supress constraining 2 lists - a=b ?

Robin Munn rmunn at pobox.com
Fri Nov 8 20:19:00 EST 2002


On Fri, 08 Nov 2002 at 10:35 GMT, HugOnline <thehugonline at yahoo.de> wrote:
> Hello,
> 
> I'm a Python - newbie and I can not solve the following problem:
> 
>>>>a=[8,7,6,5,4]   # set this list to a
>>>>b=a             # I' want to have two same lists: a and b
>>>>b.sort()        # b should be sorted
>>>>print b         # it's ok 
> [4,5,6,7,8]
>>>>print a
> [4,5,6,7,8]        # but a is sorted, too !!!  
> 
> How can I suppress the constraining of a and b? I want to have in the
> result two list - a unsorted and b sorted. Is there a switch to supress
> it?

You're confusing the name of the thing with the thing itself. In Python,
names of objects are separate from the actual objects. With your first
line, you created a list of five integers and made the name 'a' point to
that list. With your second line, you made the name 'b' point to the
same object as the name 'a'.

If you want to copy the list, use something like slice notation:

b = a[:]

This creates a copy of the list pointed to by 'a' and makes 'b' point to
that copy. That will do what you were expecting.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838



More information about the Python-list mailing list