0

I would like to calculate unique values of an iterator, but without having to build a list first. Using a list, I would do for example:

from collections import Counter
from itertools import combinations

my_counts = Counter([sum(x) for x in combinations([1,2,3,4,5])],2)

But above, a list was made, and then Counter was applied. But is there a way to keep a running tally, so that the entire list does not need to stored in memory?

user3433489
  • 911
  • 2
  • 10
  • 24

1 Answers1

0

Just feed the Counter a generator expression instead of a list:

my_counts = Counter(sum(x) for x in combinations([1,2,3,4,5], 2))

or even shorter (but map only returns a generator in Python3):

my_counts = Counter(map(sum, combinations([1,2,3,4,5], 2)))

This will not build a list in memory first.

user2390182
  • 72,016
  • 6
  • 67
  • 89