0

I have a large amount of data returned from a SQL query, then broken up into groups using itertools.groupby()

I need to skip over the first element of each group, then process the rest of them. Will calling next() on the group do this? I'm not very familiar with iterators being used this way.

for group in itertools.groupby(...):
    group.next()
    for val in group...
2
  • Yes. That should work. for val in group is really just calling group.next() until it gets StopIteration anyway.
    – zondo
    Commented Feb 25, 2016 at 18:53
  • Note that .next() doesn't exist in Python 3; it's been renamed to .__next__(). Either way, you should use the next() function instead of the method.
    – jwodder
    Commented Feb 25, 2016 at 18:56

1 Answer 1

2

The theory is sound, but your code as written won't work because (a) groupby returns an iterable of (key, iterator_over_group) pairs, not the groups directly, and (b) the next method has been renamed to __next__ in Python 3 (and you should be using the next function anyway). The correct way to write your code is:

for key, group in itertools.groupby(...):
    next(group)
    for val in group:
        ...

Not the answer you're looking for? Browse other questions tagged or ask your own question.