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
Yes there’s a small difference. There was a discussion on this at /r/python recently after this blog post explained a readability difference, that
[:]doesn’t work with generators and keeps the same type as the original.Technically, you get the same thing – a brand new list that still points to the same objects. Choose whichever one you like better (although
[:]is a bit faster). Personally I agree with the blog post thatlist(old)is more readable.To answer the comment about the specific difference, in python 3.2:
Why
list(old)is slower I think is because the slicing mechanism doesn’t need to “LOAD_GLOBAL” and “CALL_FUNCTION” on the list constructor, the entire operation is handled in C.