[Tutor] 2 problems in a small script
Kent Johnson
kent37 at tds.net
Fri Oct 12 21:18:57 CEST 2007
jim stockford wrote:
>
> On Oct 12, 2007, at 11:48 AM, Kent Johnson wrote:
>
>> If all you want to do is copy the list, then
>> lstB = lstA[:]
>> is fine, or you can use
>> lstB = list(lstA)
>
> why choose one over the other? is there a performance
> or other difference?
The timeit module helps figure out if there is a performance difference.
Slicing seems to have a slight edge over a wide range if list sizes:
src $ python -m timeit -s 'l1=range(1000)' 'l2=list(l1)'
100000 loops, best of 3: 5.12 usec per loop
src $ python -m timeit -s 'l1=range(1000)' 'l2=l1[:]'
100000 loops, best of 3: 4.27 usec per loop
src $ python -m timeit -s 'l1=range(10)' 'l2=list(l1)'
1000000 loops, best of 3: 0.487 usec per loop
src $ python -m timeit -s 'l1=range(10)' 'l2=l1[:]'
1000000 loops, best of 3: 0.258 usec per loop
src $ python -m timeit -s 'l1=range(10000)' 'l2=list(l1)'
10000 loops, best of 3: 126 usec per loop
src $ python -m timeit -s 'l1=range(10000)' 'l2=l1[:]'
10000 loops, best of 3: 108 usec per loop
Other than that I think it is personal preference, whichever you prefer.
Kent
More information about the Tutor
mailing list