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.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.