mehmet mehmet - 1 year ago 96
Python Question

Initializing a list and appending in one line

How can I initialize a list, if it is not already initialized and append to it in one line. For example,

function example(a=None):
a = a or []
return another_function(a)

How can I combine those two statements in the function into one?

I am looking for something like this, but that does not work:

function example(a):
a = (a or []).append(1)
return another_function(a)

EDIT: I don't reference
elsewhere, it is just being passed from function to function. Practically just value is important, so it is OK if it is another object with the right value. I also added a default value of None.

Answer Source
def example(a):
    return a + [1] if a else [1]

>>> example([1,2,3])
[1, 2, 3, 1]
>>> example([])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download