How do I do the following in a list comprehension?
test = [["abc", 1],["bca",2]] result = [] for x in test: if x[0] =='abc': result.append(x) else: pass result Out[125]: [['abc', 1]]
Try 1:
[x if (x[0] == 'abc') else pass for x in test] File "<ipython-input-127-d0bbe1907880>", line 1 [x if (x[0] == 'abc') else pass for x in test] ^ SyntaxError: invalid syntax
Try 2:
[x if (x[0] == 'abc') else None for x in test] Out[126]: [['abc', 1], None]
Try 3:
[x if (x[0] == 'abc') for x in test] File "<ipython-input-122-a114a293661f>", line 1 [x if (x[0] == 'abc') for x in test] ^ SyntaxError: invalid syntax
The if needs to be at the end and you don't need the pass in the list comprehension. The item will only be added if the if condition is met, otherwise the element will be ignored, so the pass is implicitly implemented in the list comprehension syntax.
Answer. Yes, an else clause can be used with an if in a list comprehension. The following code example shows the use of an else in a simple list comprehension.
Given a list comprehension you can append one or more if conditions to filter values. For each <element> in <iterable> ; if <condition> evaluates to True , add <expression> (usually a function of <element> ) to the returned list.
As it turns out, you can nest list comprehensions within another list comprehension to further reduce your code and make it easier to read still. As a matter of fact, there's no limit to the number of comprehensions you can nest within each other, which makes it possible to write very complex code in a single line.
The if
needs to be at the end and you don't need the pass
in the list comprehension. The item will only be added if the if
condition is met, otherwise the element will be ignored, so the pass
is implicitly implemented in the list comprehension syntax.
[x for x in test if x[0] == 'abc']
For completeness, the output of this statement is :
[['abc', 1]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With