pythonpython-3.xfor-loopnestedgenerator-expression

How to Check if Element exists in Second Sublist?


If I had a list like this:

L = [
           ['a', 'b'], 
           ['c', 'f'], 
           ['d', 'e']
       ]

I know that I could check if e.g. 'f' was contained in any of the sub lists by using any in the following way:

if any('f' in sublist for sublist in L) # True

But how would I go about searching through second sub lists, i.e. if the list was initialized the following way:

L = [
           [
               ['a', 'b'], 
               ['c', 'f'], 
               ['d', 'e']
           ], 
           [
               ['z', 'i', 'l'],
               ['k']
           ]
       ]

I tried chaining the for in expressions like this:

if any('f' in second_sublist for second_sublist in sublist for sublist in L)

However, this crashes because name 'sublist' is not defined.


Solution

  • First write your logic as a regular for loop:

    for first_sub in L:
        for second_sub in first_sub:
            if 'f' in second_sub:
                print('Match!')
                break
    

    Then rewrite as a generator expression with the for statements in the same order:

    any('f' in second_sub for first_sub in L for second_sub in first_sub)