You created a list with a list comprehension, then called its count
method. Instead, just create an iterator with a generator expression, then call an icount
function that takes any iterable:
diffs = (abs(a -b) for a, b in combinations(intList, 2))
print icount(diffs, 2)
It's nearly identical to your original code, but it doesn't use any extra memory.
Of course that icount
function doesn't exist, but you should be able to write it yourself.
def icount(iterable, value):
result = 0
for element in iterable:
if element == value:
result += 1
return result
… or …</p>
def ilen(iterable):
return sum(1 for _ in iterable)
def icount(iterable, value):
filtered = (elem for elem in iterable if elem == value)
return ilen(filtered)
… or …</p>
def icount(iterable, value):
return sum(elem == value for elem in iterable)
… or (using itertools recipes) …</p>
def icount(iterable, value):
return quantify(iterable, lambda elem: elem == value)
If you want, you can merge the expression into the icount
function and do it all in one line, and then you have exactly Tim Peters' answer.