Skip to content Skip to sidebar Skip to footer

Comparing Same Index In 2 Lists

I don't have a code for this because I have no idea how to do it, and couldn't find much help on Google. Is there a way to find if the same indexes on 2 lists are the same? For exa

Solution 1:

zip the lists and return the test (which returns a boolean as outcome):

[i == j for i, j in zip(x_list, y_list)]

You could use any to quickly check for the existence of a False (means the items are not the same) if you don't need the values:

any(i != j for i, j inzip(x_list, y_list))

The any version would break once a False is found meaning you may not have to traverse the whole lists except in the worst case.

Solution 2:

You can always use list comprehensions:

[True if i == j else False for i,j in zip(x_list, y_list)]. You can also check less explicit answer by Moses Koledoye, where True if i == j else False is juzt i == j

zip function will combine your lists like [(1, 1), (2, 2), (3, 'A'), (4, 'B'), (5, 5)]

Result: [True, True, False, False, True]

Also suggest to use izip from itertools if you use Python2.

Solution 3:

try this:

   [i == j for i, j in zip(x_list, y_list)]

Solution 4:

You can try with below definition if you would like to compare lists with different size. This would fetch either unique index elements or not rather than a list of True or False.

defis_uniq_lists(x_list, y_list):
    iflen(x_list) != len(y_list):
        returnFalsefor (i,j) inzip(x_list, y_list): 
        if i != j: returnFalsereturnTrue

Result:

>>>a = [1,2,3,4,5]    # Unique lists>>>b = [1,2,3,4,5]>>>List.is_uniq_lists(a,b)
True
>>>a=[1,2,3,4,5]    # Different lists>>>b=[1,2,'A','B',5]>>>List.is_uniq_lists(a,b)
False
>>>a=[1,2,3,4,5]>>>b=[1,2,3,4,5,6]    # Lists of unequal length>>>List.is_uniq_lists(a,b)
False

Solution 5:

defcompareArrayIndex(L1, L2):
    if(len(L1) == len(L2)):
        for i inrange(0, len(L2)):
            if(L1[i] > L2[i]):
                # logicelif(L1[i] < L2[i]):
                # logicelse:
                # logicreturn value

Post a Comment for "Comparing Same Index In 2 Lists"