Efficiently iterating over part of a list

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Fri Oct 13 03:35:49 EDT 2006


If I want to iterate over part of the list, the normal Python idiom is to
do something like this:

alist = range(50)
# first item is special
x = alist[0]
# iterate over the rest of the list
for item in alist[1:]
    x = item

The important thing to notice is that alist[1:] makes a copy. What if the
list has millions of items and duplicating it is expensive? What do people
do in that case?

Are there better or more Pythonic alternatives to this obvious C-like
idiom?

for i in range(1, len(alist)):
    x = alist[i]


-- 
Steven D'Aprano 




More information about the Python-list mailing list