Liang Li Liang Li - 3 months ago 21
Python Question

Refactoring Python Code

Could anyone give some suggestions on refactoring the following code to 1-2 lines so that it is concise and readable.

def func(a, b):
c = []
if a:
c.append(a)
if b:
c.append(b)
return c


I tried following:

def func(a, b):
return [a*(a is not None), b*(b is not None)]


It won't work if
a
or
b
is a dictionary, etc.

Answer
def func(a, b):
    return [x for x in [a, b] if x]
Comments