creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126974

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.

Upvotes: 1

Views: 1316

Answers (2)

vielkind
vielkind

Reputation: 2980

If you don't need to know where 'f' is located you can leverage itertools here as well.

import itertools

any('f' in x for x in itertools.chain.from_iterable(l))

This will flatten your nested lists and evaluate each list separately. The benefit here is if you have three nested lists this solution would still function without having to continue writing nest for loops.

Upvotes: 0

jpp
jpp

Reputation: 164823

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)

Upvotes: 6

Related Questions