Python – Iterate over a list and check if it’s not Empty

I have a list that I wanted to iterate over. When I used a list comprehension, it would fail if the list was None. But it would if the list was empty [].

The old and easy way of doing this was:

if tags:
	for t in tags:
		# Do stuff with t

The pythonic way of merging the if statement within the list comprehension is:

for t in [t for t in (tags or [])]:
	# Do stuff with t

If you had a dictionary, you could use a ternary condition within list comprehension:

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

OR, You can embed the ternary condition in the comprehension as well:

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

The original stack overflow post.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s