DaneSoul
DaneSoul

Reputation: 4511

Counting elements which satisfy if statement and use this counter in list comprehension in Python?

For example, we have task, select first ten even numbers in the list.

This can be easily done with simple for loop:

i = 0
list_even = []
for x in range(30):
    if x % 2 == 0 and i < 10:
        list_even.append(x)
        i += 1
print(list_even)    # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] - correct!

How is it possible to do same with list-comprehension?

I have tried to use enumerate, but it counts all elements, not only that satisfy if statement, so I can't use the index from enumerate as counter.

list_even = [x for i, x in enumerate(range(30)) if x % 2 == 0 and i < 10]
print(list_even)    # [0, 2, 4, 6, 8] - incorrect!

The task I describe is just example - I am writing article about list comprehensions and want to understand details and general solution for such class of tasks.

Upvotes: 2

Views: 433

Answers (1)

Stefan Pochmann
Stefan Pochmann

Reputation: 28596

First just filter, then count only the already filtered values?

>>> [x for i, x in enumerate(x for x in range(30) if x % 2 == 0) if i < 10]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Though islice might be a better way to say you only want the first 10:

>>> list(itertools.islice((x for x in range(30) if x % 2 == 0), 10))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Or just taking a slice of the full list, if time/space aren't an issue:

>>> [x for x in range(30) if x % 2 == 0][:10]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Upvotes: 7

Related Questions