Compare Two Lists Element-Wise in Python (2 Examples)

 

In this Python programming tutorial you’ll learn how to compare each element pair across two lists.

The post is structured as follows:

If you want to learn more about these content blocks, keep reading!

 

Example Data

In this section, we will introduce three lists as first two lists are of the same length, while the third one is longer than others.

list1 = [1, 2, 3, 4, 6]                                           # create list
list2 = [1, 2, 3, 4, 5]                                           # create list in same length 
list3 = [1, 2, 3, 4, 5, 6]                                        # create list in different length

As seen, three lists: list1, list2 and list3 have been defined, where list3 is longer than the others.

Next, we will perform an element-wise comparison between lists using the zip function. Let’s take a look!

 

Example 1: Element-Wise Comparison of Lists Using zip

The zip function will pair up the elements of two lists, allowing for a direct comparison. The enumerate function will help us keep track of the current index during iteration.

Let’s see how these two functions assist with comparing the elements pairwise when embedded into a for loop.

for i, (a, b) in enumerate(zip(list1, list2)):                    # compare list1 and list2
    if a == b:
        print(f"Element {i}: Equal")
    elif a > b:
        print(f"Element {i}: List1 is greater")
    else:
        print(f"Element {i}: List2 is greater")
# Element 0: Equal
# Element 1: Equal
# Element 2: Equal
# Element 3: Equal
# Element 4: List1 is greater

As celarly seen, the execution returned a result for each element comparison. You can call that list1 and list2 have seme lenghts. What if the lists were not in the same length?

Let’s run the same code script this time for list1 and list3 and see how the zip funciton pairs lists with different sizes.

for i, (a, b) in enumerate(zip(list1, list3)):                    # compare list1 and list3
    if a == b:
        print(f"Element {i}: Equal")
    elif a > b:
        print(f"Element {i}: List1 is greater")
    else:
        print(f"Element {i}: List3 is greater")
# Element 0: Equal
# Element 1: Equal
# Element 2: Equal
# Element 3: Equal
# Element 4: List1 is greater

You can observe how the extra element in list3 was ignored and relatedly, the same output was returned. This is because zip truncates the comparison to the shorter list, meaning the extra elements in the longer list3 are ignored.

To avoid truncating the comparison and ensure that all elements in both lists are considered, we can use the zip_longest function from the itertools module.

Let’s see how it works!

 

Example 2: Element-Wise Comparison of List Using zip & Missingness Message

In this section, we will employ itertools.zip_longest to compare list1 and list3. The advantage of zip_longest over the basic zip is evident: it does not truncate the lists. Instead, for the shorter list, it fills in with a default value None.

import itertools                                                  # import itertools module
for i, (a, b) in enumerate(itertools.zip_longest(list1, list3)):  # compare list1 and list3
    if a is None:
        print(f"Element {i}: List1 has a missing element. List3's element is {b}.")
    elif b is None:
        print(f"Element {i}: List3 has a missing element. List1's element is {a}.")
    elif a == b:
        print("Equal")
    elif a > b:
        print("List1 is greater")
    else:
        print("List3 is greater")
# Equal
# Equal
# Equal
# Equal
# List1 is greater
# Element 5: List1 has a missing element. List3's element is 6.

As the loop progresses with the help of enumerate, it checks for missing elements in either list, indicating which list lacks an element and at which position.

If both lists have elements at a particular position, they are directly compared, and the relationship is printed out.

The result provides a comprehensive understanding of the relative contents and sizes of the two lists.

 

Video & Further Resources

Do you want to learn more about the comparison of lists element-wise? Then I can recommend watching the following video instruction on my YouTube channel. In the video, I explain the Python codes of this tutorial.

 

The YouTube video will be added soon.

 

In addition, you might have a look at some of the other articles on my website. I have released numerous related posts already:

 

Summary: You have learned in this tutorial how to check the element-wise equivalence of lists in the Python programming language. In case you have any further questions, please let me know in the comments.

 

Cansu Kebabci R Programmer & Data Scientist

This page was created in collaboration with Cansu Kebabci. Have a look at Cansu’s author page to get more information about her professional background, a list of all his tutorials, as well as an overview on her other tasks on Statistics Globe.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Top