Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 493
user937284 Avatar asked Sep 14 '25 23:09

user937284


2 Answers

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.

like image 148
Volatility Avatar answered Sep 17 '25 12:09

Volatility


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]
like image 32
abarnert Avatar answered Sep 17 '25 13:09

abarnert