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

Time:12-16

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 :)

CodePudding user response:

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.

CodePudding user response:

any(...) returns a boolean value. It answers the question: "does the iterable have any element that matches the condition". So no, it cannot return the matched element itself.

If you want the matched element, it's better to write a simple loop. It's good to wrap this in a function:

def get_first_match(iter, cond):
    for item in iter:
        if cond(item):
            return item

Example usage:

print(get_first_match(list_, lambda item: 1 in item))

Note that when there's no matching item, the function will return None.

CodePudding user response:

Use an assignment expression to capture the last value evaluated by any.

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

x is repeatedly assigned the value of sublist as any iterates the generator expression, but since any stops as soon as 1 in sublist is true, the value of x after any returns will be the value that made 1 in sublist true.

The key is that sublist is local to the generator expression itself, but x is local to the scope any executes in.

This use-case is, in fact, one of the rationales provided for the scoping of the target of an assignment expression in PEP 572.

  • Related