Python compare two lists element wise | Example code

Use set() compare two lists in python and return matches in Python. Or you can use Using list comprehension.

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

Do comment if you have any doubts and suggestions on this Python compare list topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.