WoodChopper
WoodChopper

Reputation: 4375

List comprehension with else pass

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

Answers (3)

Abhishek Khedekar
Abhishek Khedekar

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

Thomas Baruchel
Thomas Baruchel

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:

  • a list in Python 2
  • a generator in Python3 (which may be useful for very long lists since you can later handle the result without overburdening the memory); if you still want a list, just wrap the filter function above with a list() constructor.

Upvotes: 9

Alex
Alex

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

Related Questions