4

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.

3
  • 1
    You can't directly. There are ways to achieve that result using itertools, but a plain for 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.dropwhile Dec 24, 2013 at 8:02
  • 3
    In other words, you want list1 = [someelement]?
    – Volatility
    Dec 24, 2013 at 8:02
  • @Volatility: Yes,I expect list1=[someelement]
    – s02
    Dec 24, 2013 at 10:57

5 Answers 5

4

Based on Volatility's solution:

list1 = [someelement] if someelement in list2 else []
2
  • While this is not a list comprehension, I think this is the best/cleanest way to solve the particular problem. Dec 24, 2013 at 9:11
  • Depends on aliasing. [someelement] will be equal to [a] (where a is the first matching element found in list2), but depending what you do with it and the types involved it may not have equivalent behaviour. Dec 24, 2013 at 10:07
3

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]
2

I understand you were looking to do this within a list comprehension, but it cannot be done.

Consider this solution. You can probably tighten this up, but I trust the code is easily understood.

list1 = []
for a in list2: 
  list1.append(a)
  if a == some_element: break
3
  • 1
    Close, but to meet the stated design (nonsensical as it is) you shouldn't append unless a == some_element. This is such an exercise in attempted mind-reading that I don't know whether or not you're on the right track. Dec 24, 2013 at 8:13
  • @PeterDeGlopper, I understand many are interpreting the question that way, but I decided to interpret it differently. Since the literal question is, as you say, nonsense... I assumed @s02 was actually asking to stop the iterative generation of the list after appending some_element. Mind-reading, agreed. :-) Dec 24, 2013 at 9:37
  • @PeterDeGlopper: I just could not understand the reason a particular question is being tagged as "nonsensical",I thought this forum is for sharing ideas/knowledge and not being judgemental about other's questions who are newbies.Although agreed,I should have been more clear with my question,which I think is easier to demand instead of making nonsensical/baseless comments...
    – s02
    Dec 25, 2013 at 8:39
2

If your 'someelement' has a fixed value, than you do not need a list comprehension even. All you have to do is :

list1 = list2[:list2.index(someelement)]

And your job is done :)

2

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.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.