Velocity Reviews > Mutability, copying lists but not sharing?

# Mutability, copying lists but not sharing?

cnb
Guest
Posts: n/a

 08-26-2008
Is it not possible to have mutability without this? I know I can use
sorted and list(reversed) instead of .sort and .reverse but if I want
to copy a list and then change that list without changing the first
one?
And there isn't a .copy function so I have to "new = [] for element in
list: new.append(element)" ?
(I guess mutability is there for performance? Because I prefer a =
sorted(a) conceptually.)

>>> a = [1,2,3]
>>> b = a
>>> b.append(4)
>>> b

[1, 2, 3, 4]
>>> a

[1, 2, 3, 4]
>>> c = "hello"
>>> d = c
>>> d += " sir!"
>>> c

'hello'
>>> d

'hello sir!'
>>>

and what is the difference between extend and + on lists?

Alan G Isaac
Guest
Posts: n/a

 08-26-2008
cnb wrote:
> And there isn't a .copy function so I have to "new = []
> for element in list: new.append(element)"?

You can do
new = list(old)
which I like for being explicit, or just
new = old[:]

> and what is the difference between extend and + on lists?

>>> a = range(3)
>>> b = a + range(3)
>>> b

[0, 1, 2, 0, 1, 2]
>>> a

[0, 1, 2]
>>> a.extend(range(3))
>>> a

[0, 1, 2, 0, 1, 2]

hth,
Alan Isaac

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is OffTrackbacks are On Pingbacks are On Refbacks are Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post Victor B. Gonzalez Python 5 10-17-2007 12:19 PM pallav C++ 5 04-18-2007 09:15 AM =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==?= Python 5 05-15-2006 11:47 AM Harry Overs C++ 4 09-30-2004 09:00 PM