Creating a Python list comprehension with an if and break

Posted on

Question :

Creating a Python list comprehension with an if and break

Is it possible to turn this code into a list comprehension?

for i in userInput:
    if i in wordsTask:
        a = i
        break

I know how to convert part of it:

[i for i in userInput if i in wordsTask]

But I don’t know how to add the break, and the documentation hasn’t been much help.

Any help would be appreciated.

Answer #1:

a = next(i for i in userInput if i in wordsTask)

To break it down somewhat:

[i for i in userInput if i in wordsTask]

Will produce a list. What you want is the first item in the list. One way to do this is with the next function:

next([i for i in userInput if i in wordsTask])

Next returns the next item from an iterator. In the case of iterable like a list, it ends up taking the first item.

But there is no reason to actually build the list, so we can use a generator expression instead:

a = next(i for i in userInput if i in wordsTask)

Also, note that if the generator expression is empty, this will result in an exception: StopIteration. You may want to handle that situation. Or you can add a default

a = next((i for i in userInput if i in wordsTask), 42)
Answered By: subtlearray

Leave a Reply

Your email address will not be published. Required fields are marked *