Nyxynyx
Nyxynyx

Reputation: 63619

Python List Comprehension and 'not in'

I'm getting started with Python and is currently learning about list comprehensions so this may sound really strange.

Question: Is it possible to use list comprehension to create a list of elements in t that is not found in s?

I tried the following and it gave me an error:

>>> t = [1, 2, 3, 4, 5]
>>> s = [1, 3, 5]
>>>[t for t not in s]

[t for t not in s]
           ^
SyntaxError: invalid syntax

Upvotes: 43

Views: 63158

Answers (4)

Lucas Ribeiro
Lucas Ribeiro

Reputation: 6282

Try this:

[x for x in t if x not in s]

You can nest any for if statements in list comprehensions. Try this identation, to get really long chains of conditionals, with a clearer intuition about what the code is doing.

my_list = [(x,a)
           for x in t
           if x not in s
           if x > 0
           for a in y
           ...]

See?

Upvotes: 74

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

I know you're asking about list comprehensions, but I wanted to point out that this specific problem would be better accomplished using sets. The result you want is the difference of set t and s:

>>> t = {1,2,3,4,5}
>>> s = {1,3,5}
>>>
>>> t - s
set([2, 4])
>>>
>>> t.difference(s)
set([2, 4])

Just hoping to expand your knowledge of the tools Python provides to you.

Upvotes: 2

MangoHands
MangoHands

Reputation: 1161

For better efficiency, use a set:

mySet = set(s)
result = [x for x in t if x not in mySet]

Testing membership of a set is done is O(1), but testing membership in a list is O(n).

Upvotes: 1

Leonardo.Z
Leonardo.Z

Reputation: 9791

[item  for item  in t if item not in s]

Upvotes: 6

Related Questions