On Sun, 5 Sep 2010 03:14:24 am Bill Allen wrote:
> Say I have and iterable called some_stuff which is thousands of items
> in length and I am looping thru it as such:
>
> for x in some_stuff
> etc...
>
> However, what if I want only to iterate through only the first ten
> items of some_stuff, for testing purposes. Is there a concise way of
> specifying that in the for statement line?
The Pythonic way is to use itertools.islice.
import itertools
for x in itertools.islice(some_stuff, 10):
blah blah blah
will stop at the end of some_stuff, or after 10 items, whichever happens
first.
islice() optionally takes the full set of arguments that ordinary list
slicing takes, so that islice(iterable, start, end, stride) is nearly
the same as list(iterable)[start:end:stride].
--
Steven D'Aprano
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor