List comprehension break statement

Viewed 896

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.

5 Answers

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:

  1. 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)
  2. use for end in [[]] to initialize a variable in list comprehension.
  3. 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.

Related