Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 962
subtlearray Avatar asked Jan 26 '12 04:01

subtlearray


People also ask

Can you use an IF statement in a list comprehension?

You can also use an if-else in a list comprehension in Python. Since in a comprehension, the first thing we specify is the value to put in a list, this is where we put our if-else.

Can you use continue in list comprehension Python?

The concept of a break or a continue doesn't really make sense in the context of a map or a filter , so you cannot include them in a comprehension.

Can you do nested list comprehension?

As it turns out, you can nest list comprehensions within another list comprehension to further reduce your code and make it easier to read still. As a matter of fact, there's no limit to the number of comprehensions you can nest within each other, which makes it possible to write very complex code in a single line.


1 Answers

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)
like image 119
Winston Ewert Avatar answered Sep 18 '22 05:09

Winston Ewert