Draconis
Draconis

Reputation: 3461

Skip the first element in Python iterable

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...

Upvotes: 0

Views: 101

Answers (1)

jwodder
jwodder

Reputation: 57470

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:
        ...

Upvotes: 2

Related Questions