Skip to content

Python compare two lists element wise | Example code

  • by

Use set() to compare two lists in Python and return matches in Python. Or you can use Using list comprehension. .This is useful for checking if two lists have the same values at each index position.

Example Comparing two lists element-wise in Python

Simple example code.

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

res = set(a) & set(b)

print(list(res))

Output:

Python compare two lists element wise

Another example

if the order is significant you can do it with list comprehensions like this:

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

res = [i for i, j in zip(a, b) if i == j]

print(list(res))

Output: [5]

Actual comparison

Comparison is not only about exact match value, but It could also be greater or fewer values. Compare the corresponding values only.

List1 = [1, 3, 4, 5]
List2 = [0, 7, 6, 5]

for x in List1:
    for y in List2:
        if x > y:
            print(x, " From List1 is greater then List2", y)
        elif x == y:
            print(x, "equal", y)
        else:
            print(x, " From List 1 is less then List2", y)

Output:

1  From List1 is greater then List2 0
1  From List 1 is less then List2 7
1  From List 1 is less then List2 6
1  From List 1 is less then List2 5
3  From List1 is greater then List2 0
3  From List 1 is less then List2 7
3  From List 1 is less then List2 6
3  From List 1 is less then List2 5
4  From List1 is greater then List2 0
4  From List 1 is less then List2 7
4  From List 1 is less then List2 6
4  From List 1 is less then List2 5
5  From List1 is greater then List2 0
5  From List 1 is less then List2 7
5  From List 1 is less then List2 6
5 equal 5

Comment if you have any doubts or suggestions on this Python compare list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *