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!).
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With