From 3e18b7fd6e6a23a90f90cc45b822fef7bdb9bcf1 Mon Sep 17 00:00:00 2001 From: Mark Pilgrim Date: Wed, 15 Jul 2009 13:02:34 -0400 Subject: [PATCH] added note about exhausting iterators --- advanced-iterators.html | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/advanced-iterators.html b/advanced-iterators.html index 20271f5..1dac3bf 100755 --- a/advanced-iterators.html +++ b/advanced-iterators.html @@ -344,8 +344,8 @@ StopIteration [(4, <itertools._grouper object at 0x00BA8BF0>), (5, <itertools._grouper object at 0x00BB4050>), (6, <itertools._grouper object at 0x00BB4030>)] ->>> groups = itertools.groupby(names, len) ->>> for name_length, name_iter in groups: +>>> groups = itertools.groupby(names, len) +>>> for name_length, name_iter in groups: ... print('Names with {0:d} letters:'.format(name_length)) ... for name in name_iter: ... print(name) @@ -365,6 +365,7 @@ Lizzie Wesley
  1. The itertools.groupby() function takes a sequence and a key function, and returns an iterator that generates pairs. Each pair contains the result of key_function(each item) and another iterator containing all the items that shared that key result. +
  2. Calling the list() function “exhausted” the iterator, i.e. you’ve already generated every item in the iterator to make the list. There’s no “reset” button on an iterator; you can’t just start over once you’ve exhausted it. If you want to loop through it again (say, in the upcoming for loop), you need to call itertools.groupby() again to create a new iterator.
  3. In this example, given a list of names already sorted by length, itertools.groupby(names, len) will put all the 4-letter names in one iterator, all the 5-letter names in another iterator, and so on. The groupby() function is completely generic; it could group strings by first letter, numbers by their number of factors, or any other key function you can think of.