Efficiently iterating over part of a list

James Stroud jstroud at mbi.ucla.edu
Fri Oct 13 03:48:54 EDT 2006


Steven D'Aprano wrote:
> 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]
> 
> 

I think this is a job for iterators:

listiter = iter(alist)

first_item_is_special = listiter.next()

for not_special_item in listiter:
   do_stuff_with(not_special_item)


Other solutions might involve enumerators:

special = [i for i in xrange(50) if not i%13]

for i,item in alist:
   if i in special:
     do_something_special_with(item)
   else:
     do_other_stuff_with(item)

James


James



More information about the Python-list mailing list