Python: Create list from variables as long as they are not None
Question:
How do I add multiple variables to a list as long as they are not None
?
If either one of them is None
, then only the other one should be added to the list.
a = "A"
b = None
list_items = [a + b]
Gives:
TypeError: (“cannot concatenate ‘str’ and ‘NoneType’ objects”,
u’occurred at index 0′)
In the above example, the components of the list will always be a
and b
. I suspect a solution that can handle an arbitrary number of variables would make use of .extend()
to empty list []
as long as the next added variable is not None
. That could be useful, but what is the simplest solution?
Answers:
You could create a function that takes arbitrary number of arguments and filters out the ones which are None
:
def create_list(*args):
return [a for a in args if a is not None]
print create_list(1, 4, None, 'a', None, 'b')
Output:
[1, 4, 'a', 'b']
You can query the variable directly for None:
a = "A"
b = None
if b != None:
list_items = [a + b]
Another method would be a list comprehension:
a = "A"
b = None
lst = [e for e in [a, b] if e]
It’s a little arcane, but this should neatly return you a list of only elements that are "truthy" – i.e. not None, non-empty string, integer greater than 0, True boolean etc.
How do I add multiple variables to a list as long as they are not None
?
If either one of them is None
, then only the other one should be added to the list.
a = "A"
b = None
list_items = [a + b]
Gives:
TypeError: (“cannot concatenate ‘str’ and ‘NoneType’ objects”,
u’occurred at index 0′)
In the above example, the components of the list will always be a
and b
. I suspect a solution that can handle an arbitrary number of variables would make use of .extend()
to empty list []
as long as the next added variable is not None
. That could be useful, but what is the simplest solution?
You could create a function that takes arbitrary number of arguments and filters out the ones which are None
:
def create_list(*args):
return [a for a in args if a is not None]
print create_list(1, 4, None, 'a', None, 'b')
Output:
[1, 4, 'a', 'b']
You can query the variable directly for None:
a = "A"
b = None
if b != None:
list_items = [a + b]
Another method would be a list comprehension:
a = "A"
b = None
lst = [e for e in [a, b] if e]
It’s a little arcane, but this should neatly return you a list of only elements that are "truthy" – i.e. not None, non-empty string, integer greater than 0, True boolean etc.