How to find same elements in exact same positions in Python?

Viewed 148

I am trying to find same elements in the same position in 2 lists in python. I've tried searching on the internet but still didn't find anything.a = [1,2,3,4,5] b = [10,2,4,3,5] For example, here, 2 and 5 are the same elements at the same positions in both lists.

Is there any way to write the script of this function in python?

4 Answers

You can try zip

a = [1,2,3,4,5]
b = [10,2,4,3,5]

list(filter(lambda e: e[0]==e[1], zip(a,b))) #[(2, 2), (5, 5)]

using list comprehension and zip you can simply check if both elements are equal.

a = [1,2,3,4,5]
b = [10,2,4,3,5]

print([x for x, y in zip(a, b) if x==y])

Output:

[2, 5]

You can use binary xor:

a = [1, 2, 3, 4, 5]
b = [10, 2, 4, 3, 5]

print([i for i, j in zip(a, b) if i ^ j == 0])

You can create the list of Boolean values for equalities using list-comprehension.

>>> a = [1,2,3,4,5]; b = [10,2,4,3,5]
>>> [i==j for i,j in zip(a,b)]

[False, True, False, False, True]

If you want the values, instead of the value of truthfulness, you can have the value in comprehension.

>>>[i for i,j in zip(a,b) if i==j]
[2, 5]
Related