0

I have two lists:

input_list = ['a','b']
existing_list = ['q','w','r']

I want to create a new list that will be equal to input_list if it's not empty else it should be equal to existing_list.

The easiest way to do this is to use the plain if-else:

if input_list:
  list_to_use = input_list
else:
  list_to_use = existing_list

Is it possible to do this in a list comprehension or in any other manner that is more concise?

list_to_use = [x if input_list else y for y in existing_list for x in input_list]

The closest I could get is with this one that produces ['a', 'b', 'a', 'b', 'a', 'b'], a wrong result.

Alex Tereshenkov
  • 3,340
  • 8
  • 36
  • 61

2 Answers2

5

You don't need a list comprehension. That's exactly what or operation does:

>>> input_list or existing_list 
['a', 'b']
>>> input_list = []
>>> 
>>> input_list or existing_list 
['q', 'w', 'r']
Mazdak
  • 105,000
  • 18
  • 159
  • 188
3

Other than or, that suggested by Kasramvd (which should be the way to do this), you can also use ternary operator.

list_to_use = input_list if input_list else existing_list
Community
  • 1
  • 1
Lafexlos
  • 7,618
  • 5
  • 38
  • 53