3

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.

user937284
  • 2,454
  • 6
  • 25
  • 29
  • 1
    You could just filter out the falsey values — `parent = [i for i in parent if i]`. – Waleed Khan Feb 16 '13 at 00:27
  • No, because you probably shouldn't be using a list in the first place – Cat Plus Plus Feb 16 '13 at 00:27
  • 1
    Do you really want `data.get('label') or None`? That will turn `0`, `[]`, `False`, etc. into `None`. Since the later code is treating any false-y `label` the same, there was no reason to convert them all to `None`. – abarnert Feb 16 '13 at 00:39
  • Thanks for your comments! @abarnert ~ Does '' also get converted to None? – user937284 Feb 16 '13 at 13:21

2 Answers2

2

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.

Volatility
  • 31,232
  • 10
  • 80
  • 89
  • +1 for Py2 vs. Py3 differences, and showing the list comprehension equivalent that works in both, and explaining what it does. – abarnert Feb 16 '13 at 01:20
  • Accepted this because of the explanation of Python2 ~ Python3 difference. Thank you! – user937284 Feb 16 '13 at 13:24
1

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]
abarnert
  • 354,177
  • 51
  • 601
  • 671