Home > database >  comparing more than two lists
comparing more than two lists

Time:10-19

I have 5 lists that I am trying to compare to each other. I wanted to know what's the efficient way to do so:

l0 = [1,2,3,4,5]
l1 = [3,4,5,6,7]
l2 = [1,2,3,4,5]
l3 = [3,3,3,5,6]
l4 = [1,2,3,4,5]

I wanted to check if l1 == l2 and so on. I can do so by using a for loop, but that does not sound efficient:


l = [l0, l1, l2, l3, l4]
for i in range(5):
    for k in range(5):
        if l[i] == l[k]:
            print(f"l{i} is equal to l{k}")
        else:
            print(f"l{i} is not equal to l{k}")

As you can see in the for loop, two lists are compared multiple times i.e. l0 is compoared to l1 once when the loop for l0 is running and second when the loop for l1 is running.

Is there an efficient way to compare the lists? And please note, the order is important to me, so therefore I cannot use set() or counter(). Anyhelp is greatly appreciated and thankyou in advance for your time and effort

CodePudding user response:

@Thomas's solution is the direct way of solving this:

Using the logic @Thomas provided:

l = [l0, l1, l2, l3, l4]
for i in range(4):
    for k in range(i   1, 5):
        if l[i] == l[k]:
            print(f"l{i} is equal to l{k}")
        else:
            print(f"l{i} is not equal to l{k}")

As in the above logic, instead of ranging by 4 in the i loop, you could range it to 5 but start at 1:

for i in range(1, 5):

And then you wouldn't need to increment i for the k range loop, make the k loop:

    for k in range(i, 5):

But itertools already done this logic for us, using itertools.combinations would reduce the length of the code and thus it looks cleaner:

from itertools import combinations
for i, k in combinations(range(5), 2):
    if l[i] == l[k]:
        print(f"l{i} is equal to l{k}")
    else:
        print(f"l{i} is not equal to l{k}")

Both codes output:

l0 is not equal to l1
l0 is equal to l2
l0 is not equal to l3
l0 is equal to l4
l1 is not equal to l2
l1 is not equal to l3
l1 is not equal to l4
l2 is not equal to l3
l2 is equal to l4
l3 is not equal to l4

CodePudding user response:

Let the k-loop start at i 1 instead of 0 so there will not be backward comparisons. And let the i loop end at 4 so that i 1 will still be a valid index.

Output:

l0 is not equal to l1
l0 is equal to l2
l0 is not equal to l3
l0 is equal to l4
l1 is not equal to l2
l1 is not equal to l3
l1 is not equal to l4
l2 is not equal to l3
l2 is equal to l4
l3 is not equal to l4
  • Related