<p>I haven't been able to find an understandable explanation of how to actually use Python's <code>itertools.groupby()</code> function.  What I'm trying to do is this:</p>
<ul>
<li>Take a list - in this case, the children of an objectified <code>lxml</code> element</li>
<li>Divide it into groups based on some criteria</li>
<li>Then later iterate over each of these groups separately.</li>
</ul>
<p>I've reviewed <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="noreferrer">the documentation</a>, but I've had trouble trying to apply them beyond a simple list of numbers.</p>
<p>So, how do I use of <code>itertools.groupby()</code>?  Is there another technique I should be using?  Pointers to good &quot;prerequisite&quot; reading would also be appreciated.</p>

The example on the Python docs is quite straightforward:
```
```
groups = []
uniquekeys = []
for k, g in groupby(data, keyfunc):
    groups.append(list(g))      # Store group iterator as a list
    uniquekeys.append(k)
```
```
So in your case, data is a list of nodes,
```
keyfunc
```
is where the logic of your criteria function goes and then
```
groupby()
```
groups the data.
You must be careful to
sort the data
by the criteria before you call
```
groupby
```
or it won't work.
```
groupby
```
method actually just iterates through a list and whenever the key changes it creates a new group.