Mutability, copying lists but not sharing?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • cnb

    Mutability, copying lists but not sharing?

    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(elem ent)" ?
    (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

    #2
    Re: Mutability, copying lists but not sharing?

    cnb wrote:
    And there isn't a .copy function so I have to "new = []
    for element in list: new.append(elem ent)"?
    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(rang e(3))
    >>a
    [0, 1, 2, 0, 1, 2]

    hth,
    Alan Isaac

    Comment

    Working...