Python Forum

Full Version: Which approach is better to copy a list?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I was reading Python Crash Course (excellent book btw!), in it, the author copies a list by slicing it, and demonstrates that the new list is independent, any change in the new list, will not be reflected in the old one. On SO, the accepted answer states the prefer method is:

new_list = list(old_list) 


because it's more readable.

On Slicing:

Quote:it is a weird syntax and it does not make sense to use it ever. ;)

I prefer using the [:], it's simple and understandable to me. Any reason why I should stop using it?
That's one guy's opinion. In my experience, [:] is pretty common. Also, the second comment on that stack overflow thread notes that [:] is much faster.
Quote:Any reason why I should stop using it?
The one time you would not want to use it is when you need a deepcopy in which [:] is a shallow copy.
(Oct-15-2017, 06:05 PM)metulburr Wrote: [ -> ]
Quote:Any reason why I should stop using it?
The one time you would not want to use it is when you need a deepcopy in which [:] is a shallow copy.

As the PCC book pointed out, if you use [:], the second list has no effect on the first list, you can add items to the second and it will not be reflected in the first. Is there more that goes on in the deep copy that I'm unaware of?
You might have another list in the list:

>>> a = [1, 2, 3]
>>> b = [3, 4, 5]
>>> c = [a, b]
>>> d = c[:]
>>> d.append(1)
>>> c
[[1, 2, 3], [3, 4, 5]]
>>> d
[[1, 2, 3], [3, 4, 5], 1]
>>> d[0].append(1)
>>> a
[1, 2, 3, 1]
>>> c
[[1, 2, 3, 1], [3, 4, 5]]
So I put list a in list c. I then copy list c into list d. I can now mess with list d without affecting list c. However, the list a that is in both list c and list d is the same list a. So if I mess with the list a through list d, it messes with the list a in list c (and the original list a). A deep copy of list d would make a copy of list a before putting it into list d.
Quote: A deep copy of list d would make a copy of list a before putting it into list d.

You mean a deep copy of list c would make a copy of list a before putting it into list d, correct?
Correct. Another lesson in why you use descriptive variable names.