[Solved] Python – Compare two list and returns values more than zero that exist in both list


You can zip the two lists and check whether both elements are > 0, then zip again to distribute the pairs to the two sub-lists

>>> a= [4, 5, 4, 0, 1, 0]
>>> b= [0, 4, 4, 0, 0, 0]
>>> pairs = [(x, y) for (x, y) in zip(a, b) if x > 0 and y > 0]
>>> sub_list_a, sub_list_b = zip(*pairs)
>>> sub_list_a, sub_list_b
((5, 4), (4, 4))

If numbers can not be < 0, then you can also just filter by all:

>>> pairs = filter(all, zip(a, b))
>>> sub_list_a, sub_list_b = zip(*pairs)
>>> sub_list_a, sub_list_b
((5, 4), (4, 4))

Note that the sublists are tuples; if you need lists, map to list:

>>> sub_list_a, sub_list_b = map(list, zip(*pairs))
>>> sub_list_a, sub_list_b
([5, 4], [4, 4])

Of course, you can also do all of the above in a single line:

sub_list_a, sub_list_b = map(list, zip(*filter(all, zip(a, b))))

solved Python – Compare two list and returns values more than zero that exist in both list