Search code examples
pythonlistlist-comprehension

Is there a way of returning the match sublist found in the any() function?


the code is:

list_ = [[1,2,3],[4,5,6],[7,8,9]]

if i try:

1 in list_

it will return false. But if i use the any() function it returns True!

any(1 in sublist for sublist in list_)

But i want it to return the sublist that the item '1' is found. I've tried things like:

if any(1 in sublist for sublist in list_):
    print(sublist)

it raise NameError: name 'sublist' is not defined

is there a way of doing it?? Thanks :)


Solution

  • You can use the list comprehension syntax, which includes an expression for filtering in it.

    In this case, you'd want:

    [sublist for sublist in list_ if 1 in sublist]

    The new list will be created dynamically, and just the elements in list_ that pass the guard expression `...if 1 in sublist``` will be included.

    Just to be complete: there is no way to get all the elements from a call to any because it stops processing the iterator as soon as it finds the first match - that is the advantage of using it over a regular comprehension or generator expression: the syntax for those do not allow one to stop the processing of an iterator once a condition is met.