Reputation: 8153
Say I have a class Node
, with attributes left
, right
, val
. Then suppose we have internal
and leaf
, where leaf
has None
for left
and right
. Then iterating through my_list = [internal, leaf]
, I only want to add the child nodes to an array only if they exist, so I would do something like
[x.left if x.left is not None for x in my_list]
Is something like this possible? When I try this I get a invalid syntax error
Upvotes: 1
Views: 33
Reputation: 19242
You're almost there! You need to switch the ordering of the for
and if
clauses:
[x.left for x in my_list if x.left is not None]
Upvotes: 1