Creating a Python list comprehension with an if and break

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)

Leave a Comment