[Tutor] iterating over less than a full list

Sander Sweers sander.sweers at gmail.com
Sat Sep 4 19:25:01 CEST 2010


On 4 September 2010 19:14, Bill Allen <wallenpb at gmail.com> 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?

You can use a slice or use a counter.

slice,

for x in some_stuff[:10]:
    etc

counter,

count = 0

for x in some_stuff:
    if x <= 10:
        print x
    else:
        break

greets
Sander


More information about the Tutor mailing list