Search code examples
pythonlist-comprehension

List comprehension where if condition is first before loop


How would you translate the following condition into a list comprehension?

a = list()
if inputs is not None:
   for i in inputs:
      a.append(my_function(i))
else:
   a.append(my_function())

I was thinking:

a = [my_function(input) for input in inputs else my_function() if inputs is not None]

but getting errors.

Note: This was just a pseudo code with pseudo names. Apologies for confusion.


Solution

  • Your if needs to be outside the list comprehension:

    a = [my_function(i) for i in inputs] if inputs is not None else my_function()
    

    I changed input to i, because input is a built-in function.