Skip to content

How to compare two lists in Python using for loop | Example code

You can compare two lists the same as other programming languages using for loop in python. You have to use 2 for loop to compare every element with another list without sorting.

Read this tutorial- Check if two lists are Equal Python

How to compare two lists in Python using for loop Example

Simple example code.

list_1 = [1, 2, 3, 4, 5]
list_2 = [1, 2, 3, 7, 8]

m_list = []

for item in list_1:
    for item1 in list_2:
        if item == item1:
            m_list.append(item)

print(m_list)

Output:

How to compare two lists in Python using for loop

Do comment if you have any doubts and suggestions on this list tutorial.

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.

2 thoughts on “How to compare two lists in Python using for loop | Example code”

  1. You did something like this here A ∩ B intersection (you still need a condition to add so you won’t have repeats in your final list to be a set intersection), how is this comparison ?
    I was expected something like the item from position 0 from the first list to be compared with the item from position 0 from second list.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading