get the first item from an iterable that matches a condition 1

get the first item from an iterable that matches a condition

a = []
item = next((x for x in a), None)

Here is what the above code is Doing:
1. The first line creates a list called a.
2. The second line creates a variable called item.
3. The third line is a generator expression. It creates a generator object, and the next() function is called on that generator.
4. The next() function returns the first item yielded by the generator. If the generator yields nothing, then next() returns the optional default value that was passed to it.

Similar Posts