Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension with else pass

Tags:

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 
like image 303
WoodChopper Avatar asked Nov 13 '15 11:11

WoodChopper


People also ask

How do you pass else in list comprehension in Python?

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.

Can else be used in list comprehension?

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.

How do you add conditions to a list comprehension in Python?

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.

Can list comprehension be nested?

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.


1 Answers

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]] 
like image 155
Alex Avatar answered Nov 10 '22 06:11

Alex