iterators and views of lists

Peter Otten __peter__ at web.de
Wed Dec 16 08:33:05 EST 2009


Paul Rudin wrote:

> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
> 
> 
>> I'm sympathetic to your request for list views. I've often wanted some
>> way to cleanly and neatly do this:
>>
>> for item in seq[1:]:
>>     process(item)
>>
>> without making an unnecessary copy of almost all of seq.
>>
> 
> I don't know how it's implemented - but presumably itertools.islice
> could provide what you're asking for?

For skipping just a few items islice() is perfect, for big offsets its O(N) 
behaviour may get annoying:

$ python -m timeit -s"from itertools import islice; N=10**5; r = range(N)" 
"for i in islice(r, N, N): pass"
100 loops, best of 3: 1.93 msec per loop

$ python -m timeit -s"from itertools import islice; N=10**6; r = range(N)" 
"for i in islice(r, N, N): pass"
10 loops, best of 3: 18.9 msec per loop

$ python -m timeit -s"from itertools import islice; N=10**7; r = range(N)" 
"for i in islice(r, N, N): pass"
10 loops, best of 3: 188 msec per loop

islice() could be changed to special-case lists and tuples, but that feels a 
bit unclean.



More information about the Python-list mailing list