How to limit the size of a comprehension?
You can use a generator expression to do the filtering, then use islice() to limit the number of iterations: from itertools import islice filtered = (i for i in a if i == 1) b = list(islice(filtered, 3)) This ensures you don’t do more work than you have to to produce those 3 elements. Note … Read more