Search code examples
pythoniterator

Doing an assignment within python next()


Is it possible to do an assignment within next() function. For an example, consider following line. It searches a text for a given list of patterns and returns True if a match is found.

foundPattern = next((True for pattern in patterns  if pattern in text), False)

Is it possible to assign the pattern which get matched to be used outside next() function.


Solution

  • Return a tuple

    retval, foundPattern = next(((True, pattern) for pattern in patterns  if pattern in text), (False, None))