Search code examples
python-3.xfor-loopif-statementany

A simpler way to do something for the 1st item of A in C that is also in B without iterating twice


I have constructed the following script in Python 3 that does what it needs to, but, it iterates through my items twice. Is there are way to the same outcome with a single iteration?

if any(A in B for A in C):
    for A in C:
        if A in B:
            # Do something with A.
            # Order of iteration is important.
            break
else:
    # Do something else

Solution

  • The most efficient way would probably to get A in a single iteration at the C-level (using filter and next) and then use it straight away.

    A = next(filter(B.__contains__, C), None)
    
    if A is not None:
        # Do something with A
    else:
        # Do something else