Negative array indicies and slice()

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Oct 29 18:02:10 EDT 2012


On Mon, 29 Oct 2012 23:40:53 +1100, Chris Angelico wrote:

> On Mon, Oct 29, 2012 at 3:52 PM, Andrew Robinson
> <andrew3 at r3dsolutions.com> wrote:
>> I am curious as to how quickly it constructs the result compared to a
>> slice operation.
>>
>> Eg:
>> a[1:5]
>> vs.
>> [ a[i] for i in xrange[1:5] ]
> 
> For the most part, don't concern yourself with performance. Go with
> functionality and readability. In the trivial case shown here, the slice
> is WAY clearer, so it should definitely be the one used; in other cases,
> the slice might simply be insufficient, so you go with whatever achieves
> your goal. Performance will usually be "good enough", even if there's a
> marginally faster way.


Slicing is about an order of magnitude faster:


[steve at ando ~]$ python2.7 -m timeit -s "x = range(100, 1000, 2)" "x
[20:40]"
1000000 loops, best of 3: 0.342 usec per loop
[steve at ando ~]$ python2.7 -m timeit -s "x = range(100, 1000, 2)" "[x[i] 
for i in xrange(20, 40)]"
100000 loops, best of 3: 3.43 usec per loop


-- 
Steven



More information about the Python-list mailing list