views:

46

answers:

3

I'm modifying some code that calls enumerate on a list declared via a list comprehension e.g.

self.groups = [Groups(self, idx) for idx in range(n_groups)]

then later:

for idx, group in enumerate(self.groups):
    # do some stuff

but when I change the enumerate call to start at the 2nd list element via the start parameter e.g.

for idx, group in enumerate(self.groups[1]):

I get an exception:

exceptions.TypeError: 'Group' object is not iterable

Could someone explain why this is?

+2  A: 

The problem: Using an indexer with a single argument on a sequence will yield a single object from the sequence. The object picked from your sequence is of type Group, and that type is not iterable.

The solution: Use the slice construct to get a new sequence of items from a specific index:

for idx, group in enumerate(self.groups[1:]):
    # do some stuff
Jørn Schou-Rode
+1  A: 

you're not starting at the second, you're trying to iterate only over the second. To start at the second item do:

for idx, group in enumerate(self.groups[1:]):
    # process
SilentGhost
+1  A: 

If your sequence is large enough than consider using islice function from itertools module, because it's more memory efficient for large sequences than slicing:

import itertools

for idx, group in enumerate(itertools.islice(self.groups, 1, None)):
    # process
Ruslan Spivak