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
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.
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.
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.
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?
[item for item in t if item not in s]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With