Python - check if object in list is None and make list

I am somehow familiar with a list in Python. But in situations where I need to check if a list is not None, the list comprehension will fail.

eg.

tags = v.tags
if tags:
    for t in tags:
        if t['Key'] == 'Name':
            # Do something

      

Now if tags are None then the following list comprehension fails. It works fine if the tags are empty / []. I would like the list to understand what None is checking.

[k for k,v in tags if tags]:

      

+4


source to share


3 answers


How about this:

[k for k in (tags or [])]

      

Let's see what happens in both cases:



  • >>> tags = None

    >>> [k for k in (tags or [])]
    []
    
          

  • tags = [1, 2, 3]

    >>> [k for k in (tags or [])]
    [1, 2, 3]
    
          


This works because it only (tags or [])

returns tags

if bool(tags) == True

. Otherwise, it returns the second argument, in this case []

even if its boolean is also equal False

. So we either iterate over tags

if they exist or an empty list if it doesn't.

+10


source


You can use a triple condition here:

([k for k, v in tags] if tags is not None else [])

      

You can also embed a ternary condition into an understanding:

[k for k, v in (tags if tags is not None else [])]

      


As a side note, it [k for k, v in tags if tags]

doesn't really behave the way you might expect. The if

list comprehension clause is evaluated at each iteration, which means that the true value is tags

checked for every item in it.



To prove it:

l = [1, 2, 3, 4, 5]

def is_empty(l):
    print("is_empty")
    return len(l) > 0

m = [i for i in l if is_empty(l)]

print(m)

      

Output:

is_empty
is_empty
is_empty
is_empty
is_empty
[1, 2, 3, 4, 5]

      

What you are semantically looking for is a built-in if

, i.e. in Python, ternary condition.

+5


source


You can test with the previous if block

if tags is not None:
   ...

      

Or short-circuiting with an empty iteration:

>>> tags = None
>>> [k for k, _ in tags or ()]
[]

      

+4


source







All Articles