Listing with the if statement

I want to compare 2 iterations and print the elements that appear in both iterations.

>>> a = ('q', 'r') >>> b = ('q') # Iterate over a. If y not in b, print y. # I want to see ['r'] printed. >>> print([ y if y not in b for y in a]) ^ 

But this gives me an invalid syntax error when ^ was placed. What is wrong with this lamba function?

+56
python if-statement list-comprehension
Mar 18 '13 at 10:46
source share
4 answers

You have the wrong order. if must be after for (if it is not in the ternary if-else )

 [y for y in a if y not in b] 

This will work:

 [y if y not in b else other_value for y in a] 
+102
Mar 18 '13 at 10:48
source share

You put if at the end:

 [y for y in a if y not in b] 

List enumerations are written in the same order as their enclosed full-sized copies, basically the above statement is translated into:

 outputlist = [] for y in a: if y not in b: outputlist.append(y) 

Your version tried to do this instead:

 outputlist = [] if y not in b: for y in a: outputlist.append(y) 

but a list comprehension must begin with at least one outer loop.

+28
Mar 18 '13 at 10:47
source share

This is not a lambda function. This is a list comprehension.

Just change the order:

 [ y for y in a if y not in b] 
+4
Mar 18 '13 at 10:47
source share

List comprehension formula:

 [<value_when_condition_true> if <condition> else <value_when_condition_false> for value in list_name] 

this way you can do it like this:

 [y for y in a if y not in b] 

For demonstration purposes only: [y if y is not in b else False for y in a]

+3
Sep 09 '16 at 9:49 on
source share



All Articles