Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the first N elements of a list, until a condition is satisfied

Tags:

python

list

I have a list of objects, and I want to take the beginning of the list up until the first object that meets a simple condition (like imp[1] == 'conversion' when imp is some element in the list).

An easy way would be: initialize a new list, iterate through the original list, and at each step append the current element and check the condition on the current element. If the condition is not satisfied then continue, and if it is satisfied then break.

new_list = []
for ele in old_list:
    new_list.append(ele)
    if condish(ele):
        break

But this seems inefficient in memory, runtime, and code (the big three!).

like image 652
tscizzle Avatar asked Oct 24 '25 00:10

tscizzle


1 Answers

You can try this:

for idx, el in enumerate(your_list):
    if satisfies_condition(el):
        return your_list[:idx]

which will save you the cost of creating a new list in memory.

Or you can use itertools.takewhile

return list(itertools.takewhile(not_condition, your_list))
like image 134
Adam Smith Avatar answered Oct 26 '25 14:10

Adam Smith