Alex Tereshenkov
Alex Tereshenkov

Reputation: 3620

Python list comprehension with two lists: evaluate lists

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

Answers (2)

Lafexlos
Lafexlos

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

Kasravnd
Kasravnd

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

Related Questions