Reputation: 4375
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
Upvotes: 25
Views: 26697
Reputation: 76
I added the if statement after the for loop and it worked for my use case.
data = [a for a in source_list if (your_condition)]
Upvotes: 1
Reputation: 7507
As a complement to Jaco's answer; it is nice to know about the filter
command because what you basically want is filtering a list:
filter( lambda x: x[0]=='abc', test)
which returns:
filter
function above with a list()
constructor.Upvotes: 9
Reputation: 21766
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]]
Upvotes: 55