If you insist on using list comprehension with break
, you can achieve your goal by this hackish way:
(I find your question is kind of ambiguous, return all the elements util met someelement
, or just return first someelement
. So I write two versions.)
list2 = [1, 2, 3, 3, 4, 3, 5]
someelment = 3
list1 = [a for end in [[]] for a in list2
if not end and not (a == someelment and end.append(42))]
# output: [1, 2, 3]
list1 = [a for end in [[]] for a in list2
if not end and a == someelment and not end.append(42)]
# output: [3]
Explanation for tricks:
- The key point is building an
end
condition in list comprehension, exclude rest element when end
is not empty. (actually not break out, but indeed in logic)
- use
for end in [[]]
to initialize a variable in list comprehension.
- use lazy explanation in
and/or
to divide branch logics.
Notice, it is just a study and exploit of list comprehension, may gives you some inspirations, and should not be used in production code.
itertools
, but a plainfor
loop is probably easier. Assuming your situation is actually complex enough that direct assignment as Volatility describes below doesn't work. If you really want to use a list comprehension,dropwhile
is the place to start: docs.python.org/2/library/itertools.html#itertools.dropwhilelist1 = [someelement]
?