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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With