Issue
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
Solution
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?
Answered By - Lucas Ribeiro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.