Leo_44583
Leo_44583

Reputation: 45

Is it possible to limit the length of a conditional list comprehension in Python?

I am doing a conditional list comprehension e.g. newlist = [x for x in list if x % 2 == 0]. I want to limit the length of the resulting list to a specific number.

Is this possible without first comprehending the entire list and then slicing it?

I imagine something that has the functionality of:

limit = 10
newlist = []

for x in list:

    if len(newlist) > limit:
        break 

    if x % 2 == 0:
        newlist.append(x)

Slicing the original list (e.g. [x for x in list[:25] if x % 2 == 0] is not possible, as the if condition does not return True in any predictable intervals in my specific use case.

Many thanks in advance.

Upvotes: 3

Views: 385

Answers (2)

thanosp
thanosp

Reputation: 25

Since you are creating a list with the list comprehension you can slice your list directly after it is created.

[x for x in list[:25] if x % 2 == 0][:limit]

Upvotes: -2

orlp
orlp

Reputation: 117846

Please don't name any variables list as it shadows the built-in list constructor. I used li as a replacement for the input list here.

import itertools as it

gen = (x for x in li if x % 2 == 0)  # Lazy generator.
result = list(it.islice(gen, 25))

Upvotes: 9

Related Questions