Normal list comprehensions occur this way:
new_list = [f(x) for x in l]
What is the most succinct and readable way to create new list in Python similar to this:
new_list = [f(x) while condition is True]
I would probably wrap it in a generator-function:
def generate_items():
while condition:
yield f(x)
new_list = list(generate_items)
Use itertools:
import itertools as it
new_list = map(f, it.takewhile(condition, l))
it is the same like
new_list = [f(x) for x in it.takewhile(lambda x: condition(x), l)]
Keep it simple:
new_list = []
while condition:
new_list.append(f(x))
There is no benefit to forcing something into a single expression when it is more clearly written as separate statements.
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