I'm trying to learn Python comprehensions, but I'm stuck. I'm trying to increase my
count variable when the condition is
return that count after the loop. Here is my code:
list = [1,2,4,5,7,8,10] d = 3 count = 0 return [count for x in range(len(list)) if list[x] + d in list and list[x] + 2 * d in list]
"0" each time my condition is
True. When I try to add
count += 1 in the comprehension it's giving me a
Comprehensions don't work that way. Conceptually, they allow you to set and filter the individual elements of a list, not accumulate into a single variable.
There is a standard idiom for getting around that though. You basically make an iterable of booleans for your condition, or just retain ones for all the elements you want and discard the others, then
sum over that.
As a further improvement, I would recommend using a generator expression rather than a list comprehension. It looks almost the same, but supports lazy evaluation. This means that you get all the benefits of the one-liner, without having to store the list of flag values in memory.
Here is how the first option would look:
L = [1,2,4,5,7,8,10] count = sum((x + d in L and x + 2 * d in L) for x in L)
The second option would look like this:
L = [1,2,4,5,7,8,10] count = sum(1 for x in L if (x + d in L and x + 2 * d in L))
Notice that I renamed your variable
L so it wouldn't shadow the builtin function.