Python: How to get the length of itertools _grouper

Just because you call it clusterList doesn't make it a list! It's basically a lazy iterator, returning each item as it's needed. You can convert it to a list like this, though:

clusterList = list(clusterList)

Or do that and get its length in one step:

length = len(list(clusterList))

If you don't want to take up the memory of making it a list, you can do this instead:

length = sum(1 for x in clusterList)

Be aware that the original iterator will be consumed entirely by either converting it to a list or using the sum() formulation.


clusterList is iterable but it is not a list. This can be a little confusing sometimes. You can do a for loop over clusterList but you can't do other list things over it (slice, len, etc).

Fix: assign the result of list(clusterList) to clusterList.