Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Add item to list until a condition is true

Tags:

python

list

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]
like image 277
Xolve Avatar asked May 04 '11 12:05

Xolve


3 Answers

I would probably wrap it in a generator-function:

def generate_items():
    while condition:
        yield f(x)
new_list = list(generate_items)
like image 186
Björn Pollex Avatar answered Sep 19 '22 23:09

Björn Pollex


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)]
like image 33
eumiro Avatar answered Sep 21 '22 23:09

eumiro


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.

like image 26
Duncan Avatar answered Sep 18 '22 23:09

Duncan