[Tutor] iterating over less than a full list

Dave Angel davea at ieee.org
Sun Sep 5 10:26:58 CEST 2010


Bill Allen wrote:
> Thanks to everyone who replied.   Some of the methods presented where some I
> had thought of, others were new to me.   Particularly, I did not realize I
> could apply a slice to a list.   The for x in some_stuff[:value] form worked
> very well for my purposes.  I can also see I need to look into the itertools
> module and see what goodies are to be found there.
>
> -Bill
>   
You're certainly welcome.

One advantage of itertools islice() is that it works on a generator (for 
example), not just on a list, tuple, string,etc..  For example, if you 
have a generator that generates all prime numbers, there's no way to 
turn that into a list, because it would be infinite in size.  Thus the 
usual [:10] syntax won't work on it.  But islice() will.

DaveA





More information about the Tutor mailing list