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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With