Reputation: 3620
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.
Upvotes: 0
Views: 116
Reputation: 7735
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
Upvotes: 3
Reputation: 107347
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']
Upvotes: 5