Checking whether 2 list has same value or value,index

Viewed 51

I have this 2 list

a = [3,9,1,4,5]
b = [7,2,1,0,1]

Im trying to print a line based on some condition (same value or same index and value in 2 list), and the output should be

"Same Value(for duplicate number)"
"Same Value + Index(for duplicate number and same index)"

I tried using iteration and if like this

for x in a:
    for y in b:
        if x == y:
            if (a.index(x) == b.index(y)):
                print("Same Value + Index")
            else:
                print("Same Value")

but somehow the output shows this :

Same Value + Index
Same Value + Index
[Finished in 0.4s]

Or maybe is there any easier way for this? Thank you!

2 Answers

Your logic is faulty in looking up the number:

for x in a:
    for y in b:
        if x == y:
            if (a.index(x) == b.index(y)):

index finds the first occurence of the value. Your desired output depends on knowing which index you have. Instead, keep track of both value and index:

for x_idx, x in enumerate(a):
    for y_idx, y in enumerate(b):
        if x == y:
            if x_idx == y_idx:   # This uses the current index

The reason that you are seeing the printout twice is that list.index returns the index of the first occurrence of a value in the list, not the "current" one. So when your second list is at index 4 and the first one is at index 2, b.index(1) returns 2, not 4, and the second printout happens.

You should keep track of your current location:

for i, x in enumerate(a):
    for j, y in enumerate(b):
        if x == y:
            if i == j:
                print("Same Value + Index")
            else:
                print("Same Value")

If all you care about is the number of entries that match each condition:

both_match = len(set(enumerate(a)) & set(enumerate(b)))

Getting the same number of "anything matches" is marginally trickier. You can use collections.Counter to get the numbers just right:

ca = Counter(a)
cb = Counter(b)
value_match = sum(ca[k] * cb[k] for k in ca.keys() & cb.keys())
Related