Best way to create a copy of a list
Jorge Godoy
godoy at ieee.org
Tue Apr 4 07:38:38 EDT 2006
"Frank Millman" <frank at chagford.com> writes:
> Interesting. My results are opposite.
I got the same here (cPython 2.4.1):
godoy at jupiter ~ % python -mtimeit -s "data=[range(100)]*100; row = []" "row[:] = data[23]"
1000000 loops, best of 3: 1.15 usec per loop
godoy at jupiter ~ % python -mtimeit -s "data=[range(100)]*100" "row = data[23][:]"
100000 loops, best of 3: 1.42 usec per loop
godoy at jupiter ~ % python -mtimeit -s "data=[range(100)]*100" "row = list(data[23])"
100000 loops, best of 3: 1.93 usec per loop
godoy at jupiter ~ %
> If they are all equivalent from a functional point of view, I lean
> towards the second version. I agree with Rune that the third one is
> nicer to read, but somehow the [:] syntax makes it a bit more obvious
> what is going on.
I prefer the third option for readability. It makes it clear that I'll get a
*new* list with the 23rd row of data. Just think: how would you get the 1st
column of the 23rd row?
>>> a = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
>>> a
[[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
>>> a[1]
[2, 3]
>>> a[1][1]
3
>>> a[1][:]
[2, 3]
>>>
Someone might think that the "[:]" means "all columns" and the syntax to be
equivalent to "data[23]".
--
Jorge Godoy <godoy at ieee.org>
"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.
More information about the Python-list
mailing list