Python - Optional list values - A more pythonic way?
list, optional-values, python
Solution
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.
Problem
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.