Search code examples
pythoncomparisonlist-comprehension

Comparing each element of a list to their corresponding index in another


I have a list:

list1=[1,2,3,4,5,6]

I need to compare this to a series of other lists:

list2=[[0,0,0,0,0,0],[0,1,2,3,4,5],[2,2,2,2,2,2],[5,4,3,2,1,0]]

and flag any of these in which every value in list1 is greater than the value of its corresponding index in list2[n] i.e:

list1[0]>list2[n][0], list1[1]>list2[n][1], list1[2]>list2[n][2], list1[3]>list2[n][3], list1[4]>list2[n][4], list1[5]>list2[n][5]

Here, it should return TRUE, TRUE, FALSE, FALSE

list1 and list2[n] are always of the same length, but this length can differ.


Solution

  • Use zip and list comprehension to get a pair of elements from list1 and list2[n] and then use all to check if for all pairs (x,y), x>y

    >>> list1=[1,2,3,4,5,6]
    >>> list2=[[0,0,0,0,0,0],[0,1,2,3,4,5],[2,2,2,2,2,2],[5,4,3,2,1,0]]
    >>> [all(x>y for x,y in zip(list1,lst)) for lst in list2]
    [True, True, False, False]
    

    If list1 and list2[n] are of unequal sizes, replace zip with itertools.zip_longest

    >>> from itertools import zip_longest
    >>> [all(x>y for x,y in zip_longest(list1,lst, fillvalue=0)) for lst in list2]
    [True, True, False, False]