user937284
user937284

Reputation: 2634

Python - Optional list values - A more pythonic way?

I'd like to know if there is a more pythonic way to declare a list with an optional value?

title = data.get('title')
label = data.get('label') or None

if label:
   parent = [title, label]
else:
   parent = [title]

Thanks in advance.

Upvotes: 4

Views: 2154

Answers (2)

abarnert
abarnert

Reputation: 366103

You could even merge this all into one line:

parent = [data[k] for k in ('title', 'label') if data.get(k)]

Or, if you only want to skip missing values, not all falsish values:

parent = [data[k] for k in ('title', 'label') if k in data]

Upvotes: 1

Volatility
Volatility

Reputation: 32310

This will work in Python 2.

title = data.get('title')
label = data.get('label')

parent = filter(None, [title, label])

Use list(filter(...)) in Python 3, since it returns a lazy object in Python 3, not a list.

Or parent = [i for i in parent if i], a list comprehension which works in both versions.

Each snippet filters out the falsish values, leaving you only the ones that actually contain data.

Upvotes: 3

Related Questions