old = [1, 2, 3]
What is the difference between the following two lines (if there is any)?
new = old[:]
new = list(old)
Update I had already accepted ubershmekel's answer but later I've learned an interesting fact: [:]
is faster for small list (10 elements) but list()
is faster for larger list (100000 elements).
~$ python -S -mtimeit -s "a = list(range(10))" "a[:]"
1000000 loops, best of 3: 0.198 usec per loop
~$ python -S -mtimeit -s "a = list(range(10))" "list(a)"
1000000 loops, best of 3: 0.453 usec per loop
~$ python -S -mtimeit -s "a = list(range(100000))" "a[:]"
1000 loops, best of 3: 675 usec per loop
~$ python -S -mtimeit -s "a = list(range(100000))" "list(a)"
1000 loops, best of 3: 664 usec per loop
Python copy() method copies the list and returns the copied list. It does not take any parameter and returns a shallow copy of the list. A shallow copy is the one that does not show any modification on the original list.
The Python copy() method creates a copy of an existing list. The copy() method is added to the end of a list object and so it does not accept any parameters. copy() returns a new list.
Explanation. There are two semantic ways to copy a list. A shallow copy creates a new list of the same objects, a deep copy creates a new list containing new equivalent objects.
Python List Copy Not Working. The main reason why the list. copy() method may not work for you is because you assume that it creates a deep copy when, in reality, it only creates a shallow copy of the list.
If old is not a list, old[:] will be all the elements of old in the same kind of container as old (maybe a tuple or a string), while list(old) will be a list with the same elements.
I.e. if old is the string 'foo', old[:] will be the string 'foo', while list(old) wille be the list ['f', 'o', 'o'].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With