Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 819
Nyxynyx Avatar asked Oct 22 '13 01:10

Nyxynyx


People also ask

Should you use list comprehensions?

List comprehensions are useful and can help you write elegant code that's easy to read and debug, but they're not the right choice for all circumstances. They might make your code run more slowly or use more memory.

Is list comprehension possible in Python?

List comprehension in Python is an easy and compact syntax for creating a list from a string or another list. It is a very concise way to create a new list by performing an operation on each item in the existing list. List comprehension is considerably faster than processing a list using the for loop.

Does list comprehension use less memory?

So while list comprehensions use less memory, they're probably significantly slower because of all the resizes that occur. These will often have to copy the list backbone to a new memory area.


2 Answers

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?

like image 54
Lucas Ribeiro Avatar answered Sep 19 '22 14:09

Lucas Ribeiro


[item  for item  in t if item not in s] 
like image 39
Leonardo.Z Avatar answered Sep 19 '22 14:09

Leonardo.Z