0

The following code:

#!/usr/bin/python

def func(listtt):
    a.reverse()

a = [1, 2, 3]
b = a
print a, b

func(a)
print a, b

a = [1, 2, 3]
b = a + []
print a, b

func(a)
print a, b

produces the output of:

[1, 2, 3] [1, 2, 3]
[3, 2, 1] [3, 2, 1]
[1, 2, 3] [1, 2, 3]
[3, 2, 1] [1, 2, 3]

I understand that in the first example, a and b both point to the same list. My question is how do I create a new identical list object? If i have a list, is b = a + [ ] the best way to create two separate but identical instances of the list? I want to create two variables that point to two different lists/objects that have the exact same values. How do I do that?

Also, how do I know which operations create a new list and which change the current list? I know append changes the list and addition adds the two lists and creates a new one. I found a list of possible operations in https://docs.python.org/3.4/library/stdtypes.html#mutable-sequence-types, but which operations do which?

user1801359
  • 422
  • 1
  • 4
  • 14

2 Answers2

3

To get a shallow copy of a list:

b = a[:]  # There are various other options such as list(a), copy.copy(a) etc.

a and b are now identical, but don't point to the same reference.


The ones that modify the list in-place will be methods of list, such as .sort(). You know that a new value is being assigned if it is done with the = operator.

anon582847382
  • 19,907
  • 5
  • 54
  • 57
  • 1
    Alternatively you could do: `new_list = copy(old_list)`. That might be semantically cleaner than the slicing trick, but both will work. This question has been asked a lot of times already and I am pretty sure you could have found the answer with a simple search. – Roy Prins Apr 17 '14 at 16:24
2

There is lot of things to copy or clone a list:-

  • You can slice it:

    new_list = old_list[:]

    Alex Martelli's opinion (at least back in 2007) about this is, that it is a weird syntax and it does not make sense to use it ever. ;) (In his opinion, the next one is more readable).

    • You can use the built in list() function:

      new_list = list(old_list)

  • You can use generic copy.copy():

    import copy
    new_list = copy.copy(old_list)
    

    This is a little slower than list() because it has to find out the datatype of old_list first.

  • If the list contains objects and you want to copy them as well, use generic copy.deepcopy():

    import copy
    new_list = copy.deepcopy(old_list)
    

Obviously the slowest and most memory-needing method, but sometimes unavoidable.

For more details, take a look at this answer.

Community
  • 1
  • 1
shiminsh
  • 1,224
  • 15
  • 14