How do I compare one list against the other in Python?

Viewed 36

I want to compare list I1 against I2 and append elements which are less than or equal to the specific element in I1. But I am running into an error. I show the desired output for clarity. Thanks in advance for the help.

I1= [1, 4, 5, 8]


I2 = [2, 3, 5, 6]

J = [i for i in I1 if i <= I2]
print(J)

The error is

in <listcomp>
    J = [i for i in I1 if i <= I2]

TypeError: '<=' not supported between instances of 'int' and 'list'

The desired output is

Output=[[],[2,3],[2,3,5],[2,3,5,6]]
2 Answers
[[x for x in I2 if x < y] for y in I1]

I use this compact writing because you tried to do the same. But of course, you should write less-pythonesque but more explicit algorithm if you are more confortable with. For example with intermediate functions

For example

def lessThan(ref, I):
   return [x for x in I if x<ref]

J=[lessThan(x, I2) for x in I1]
I1= [1, 4, 5, 8]
I2 = [2, 3, 5, 6]

J = [[i2 for i2 in I2 if i2 <= i1] for i1 in I1]
Related