Maryam
Maryam

Reputation: 73

List Comprehension but on list selected for iteration based on condition

I am having two lists list1 and list2 as:

list1 = [4, 3, 20, 10]
list2 = ['a', 'f', 'd', 'b']

I want to create a new list result based on the condition that if my condition num==10 is True, then result should be holding the content from list1 else it should be holding the content from list2. Below is the code I tried:

num = 10
result = [element for element in list1 if num == 10 else list2]

But this is raising SyntaxError. How should I achieve this?

Expected output for above code is:

[4, 3, 20, 10]  # stored in `result`

Upvotes: 3

Views: 92

Answers (2)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48120

If you only want to create a new list result based on your condition num==10, you may simply do (no need of list comprehension):

>>> result = (list2, list1)[num==10]
>>> result
[4, 3, 20, 10]

Above result is based on the fact that Python treats boolean value True and False as 1 and 0 respectively. So, we are fetching the desired list from tuple based on the condition.

Other alternatives to perform the same task:

# Alternative 1: Using your `if`/`else` logic
result = (list1 if num == 10 else list2)

# Alternative 2: using `and`/`or` logic
result = (num == 10 and list1) or list2

If list comprehension is must to use for you (may be to perform some operation on the elements), then you may use list comprehension with any of the above condition as:

>>> num = 10
>>> list1 = [4, 3, 20, 10]
>>> list2 = ['a', 'f', 'd', 'b']

# Using tuple of lists with boolean index
>>> result = [element for element in (list2, list1)[num==10]]
>>> result
[4, 3, 20, 10]

# Using `if`/`else` logic
>>> result = [element for element in (list1 if num == 10 else list2)]
>>> result
[4, 3, 20, 10]

# Using using `and`/`or` logic
>>> result = [element for element in (num == 10 and list1) or list2]
>>> result
[4, 3, 20, 10]

Upvotes: 3

jonrsharpe
jonrsharpe

Reputation: 122154

You're just missing some parentheses:

result = [element for element in (list1 if num == 10 else list2)]

A list comprehension can have a filtering condition (comp_if in the language reference) as follows:

[a for a in b if c]

In your current version, list1 is b and num == 10 is c, but your additional else list2 is syntactically invalid.

You need to be explicit that your conditional expression is all part of b, which you can do with parentheses.

Upvotes: 5

Related Questions