Efficiently iterating over part of a list

2006-10-13 Thread Steven D'Aprano
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

Re: Efficiently iterating over part of a list

2006-10-13 Thread James Stroud
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

Re: Efficiently iterating over part of a list

2006-10-13 Thread James Stroud
James Stroud wrote: 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

Re: Efficiently iterating over part of a list

2006-10-13 Thread Ziga Seilnacht
Steven D'Aprano wrote: [snip] 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,

Re: Efficiently iterating over part of a list

2006-10-13 Thread Peter Otten
Steven D'Aprano wrote: Are there better or more Pythonic alternatives to this obvious C-like idiom? for i in range(1, len(alist)): x = alist[i] For small start values you can use itertools.islice(), e. g: for x in islice(alist, 1, None): # use x You'd have to time at what point

Re: Efficiently iterating over part of a list

2006-10-13 Thread Duncan Booth
Steven D'Aprano [EMAIL PROTECTED] wrote: 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? I think you are worrying prematurely. On my system slicing one element off the front

Re: Efficiently iterating over part of a list

2006-10-13 Thread Paul Rubin
Steven D'Aprano [EMAIL PROTECTED] writes: for i in range(1, len(alist)): x = alist[i] a2 = iter(alist) a2.next() # throw away first element for x in a2: ... -- http://mail.python.org/mailman/listinfo/python-list