title: Why can't I get the second to last result of an iterator in Python?
body: <p>I've spent hours trying to debug this code.  I want to get the second-to-last element of a list.</p>
  
  <pre><code>for x, y in itertools.groupby(range(0,10), lambda x: int(x / 3)):
      print("the group's key is %d and values are %s" % (x, ','.join(map(str,y))))
  
  temp = itertools.groupby(range(0,10), lambda x: int(x / 3))
  the_last_one = None
  second_to_last = None
  for x,y in temp:
      second_to_last = the_last_one
      the_last_one = y
  print(next(iter(second_to_last)))
  </code></pre>
  
  <p>The output of the first part, for demonstration, is:</p>
  
  <pre><code>the group's key is 0 and values are 0,1,2
  the group's key is 1 and values are 3,4,5
  the group's key is 2 and values are 6,7,8
  the group's key is 3 and values are 9
  </code></pre>
  
  <p>The goal in the second part is to output the first element in the second-to-last group.  I expect <code>6</code> but instead, I get the exception <code>StopIteration</code>.  If I change the last line to:</p>
  
  <pre><code>print(next(the_last_one))
  </code></pre>
  
  <p>then I get the expected result of <code>9</code>.  Using a list of tuples with the same structure as the output of <code>groupby</code> works, too.  This code only fails on iterators.</p>