Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list copy: is there a difference between old[:] and list(old)?

Tags:

python

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
like image 821
bpgergo Avatar asked Nov 09 '11 15:11

bpgergo


People also ask

What happens when you copy a list in Python?

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.

What does Copy () do in Python?

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.

How many ways can you copy a list in Python?

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.

Why is copy () not working Python?

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.


1 Answers

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'].

like image 95
Rasmus Kaj Avatar answered Oct 04 '22 16:10

Rasmus Kaj