Danny Cabrera
Danny Cabrera

Reputation: 91

How to write for loops in a "pythonic" way

I would like to know if there is a "python-ic" way to write the following nested forloops with if statements:

nonelist = []

for i in testlist:
    for e in i:
        if e == None:
            nonelist.append(i)

Upvotes: 1

Views: 211

Answers (2)

Prune
Prune

Reputation: 77837

Depending on the specific application, there might be better logic. However, for your abstract problem, you'd be more Pythonic using a direct construction: the *list comprehension".

nonelist = [i for i in testlist if any([e is None for e in i]) ]

This isn't quite the same as your code: if there are multiple None values in i, then your code appends i for each occurrence; mine adds it only once.

@Austin's improvement:

nonelist = [i for i in testlist if None in i]

Upvotes: 3

heemayl
heemayl

Reputation: 42007

You can generate a flat iterator using itertools.chain and check items from there whether they are None:

[i for i in itertools.chain.from_iterable(testlist) if i is None]

Example:

In [389]: testlist = [[1, 2, 3, None], [4, 5, None, None]]                                                                                                                                                  

In [390]: [i for i in itertools.chain.from_iterable(testlist) if i is None]                                                                                                                                 
Out[390]: [None, None, None]

FWIW None is singleton, so you should use identity (is) test on them instead of eqality test (==).

Upvotes: 4

Related Questions