Mutability, copying lists but not sharing?

Discussion in 'Python' started by cnb, Aug 26, 2008.

  1. cnb

    cnb Guest

    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?
    cnb, Aug 26, 2008
    #1
    1. Advertising

  2. cnb

    Alan G Isaac Guest

    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
    Alan G Isaac, Aug 26, 2008
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Edward C. Jones

    Mutability problem when subclassing tuple

    Edward C. Jones, Feb 19, 2004, in forum: Python
    Replies:
    2
    Views:
    588
    Shalabh Chaturvedi
    Feb 19, 2004
  2. ex_ottoyuhr

    Mutability of function arguments?

    ex_ottoyuhr, Dec 8, 2005, in forum: Python
    Replies:
    17
    Views:
    461
    Fredrik Lundh
    Dec 8, 2005
  3. gigs

    list mutability

    gigs, Feb 18, 2008, in forum: Python
    Replies:
    1
    Views:
    227
    John Machin
    Feb 18, 2008
  4. named tuple mutability

    , May 14, 2008, in forum: Python
    Replies:
    10
    Views:
    442
    Bruno Desthuilliers
    May 15, 2008
  5. kj
    Replies:
    4
    Views:
    403
    Arnaud Delobelle
    Oct 7, 2010
Loading...

Share This Page