Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension break statement

Tags:

python

How can I stop the iteration of list comprehension when a particular element is found For example:

list1=[a for a in list2 if a==someelement]

As soon as "a equals someelement",list1 should be set to a and no further iterations should be executed.

like image 539
s02 Avatar asked Dec 11 '22 08:12

s02


2 Answers

Based on Volatility's solution:

list1 = [someelement] if someelement in list2 else []
like image 174
Angry Cat Avatar answered Jan 02 '23 20:01

Angry Cat


You might want to use takewhile.

>>> import itertools
>>> print(list(itertools.takewhile(lambda x: x<42, [2, 3, 4, 42, 5, 6, 7])))
[2, 3, 4]
like image 38
Matthias Avatar answered Jan 02 '23 21:01

Matthias