Skip to content
  • YouTube
  • FaceBook
  • Twitter
  • Instagram

Data Analytics Ireland

Data Analytics and Video Tutorials

  • Home
  • Contact
  • About Us
    • Latest
    • Write for us
    • Learn more information about our website
  • Useful Links
  • Glossary
  • All Categories
  • Faq
  • Livestream
  • Toggle search form
  • Free ways to Extract Data from Files Livestream
  • How to show percentage differences between files in Python CSV
  • how to insert data into a table in SQL SQL
  • TypeError: ‘NoneType’ object is not iterable class
  • How to Pass a Javascript Variable to Python using JSON Flask
  • How to Create an XML file from Excel using Python Python
  • TypeError: ‘float’ object is not callable Python
  • How to group your data in Tableau data visualisation

how to compare two lists in Python

Posted on January 26, 2021January 26, 2021 By admin No Comments on how to compare two lists in Python

Estimated reading time: 2 minutes

Often you are going to be asked to compare lists, and you need a quick way to complete.

Here we are going to take through three ways to complete this, if you have more comment below.

Looping to find common values between lists

A simple loop can help you find data that is common to two lists:

# compare for similar values
list1 = ["1", "2", "3", "4"]
list2 = ["1", "2", "3", "4", "5"]

for i in list1:
    for j in list2:
        if i in j:
            print(i)

which yields:

1
2
3
4

Compare for an item in one list and not in the other

There maybe times you wish to find only the values that are in one list and not the other.

Below we use a one line piece of code using list comprehension, which does the same as a loop:

list1 = ["1", "2", "3", "4"]
list2 = ["1", "2", "3", "4", "5"]
for item in [x for x in list2 if x not in list1]:
    print(item)

which gives the result of:

5

comparing lists using the set method

The third way uses python sets, which essentially finds the intersection between two lists, like a Venn diagram.

Here we use set to find what values are not common to each list by using subtraction:

list1 = ["1", "2", "3", "4"]
list2 = ["1", "2", "3", "4", "5"]
a = set(list1)
b = set(list2)
c = b-a
print(c)

which gives you:

{'5'}

Alternatively you could find what is common to both:

list1 = ["1", "2", "3", "4"]
list2 = ["1", "2", "3", "4", "5"]
a = set(list1)
b = set(list2)
c = a.intersection(b)
print(c)

and your result will be:

{'1', '3', '4', '2'}

Remember that using sets will return them unordered, if you want them ordered then apply the following to the above code:

a = set(list1)
b = set(list2)
c = a.intersection(b)
d=sorted(c)
print(type(d))
print(d)

and the output will be:

<class 'list'>
['1', '2', '3', '4']

One thing to note that the sorted method above returns the set as a list not as a set.

There are plenty of resources online where you can learn about sets.

Python Lists Tags:compare lists, List comprehension, python loops, python sets, set intersection, Venn diagram

Post navigation

Previous Post: TypeError: type object is not subscriptable
Next Post: ValueError: invalid literal for int() with base 10

Related Posts

  • YouTube channel lists – Python Lists Python Lists
  • How To Run Python Validation From Javascript Javascript
  • ValueError: Columns must be same length as key exception handling
  • TypeError: Array() Argument 1 Must Be A Unicode Character, Not List array
  • How Would You Change The Name Of a Key in a Python Dictionary Python
  • How To Delete a Set of Keys From a Python Dictionary python dictionaries

Leave a Reply Cancel reply

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

Select your language!

  • हिंदी
  • Español
  • Português
  • Français
  • Italiano
  • TypeError: ‘list’ object is not an iterator Python
  • R Tutorial: How to pass data between functions R Programming
  • how to create an instance of a class class
  • ValueError: pattern contains no capture groups Value Error
  • Python Tutorial: How to create charts in Excel Python Tutorial
  • How to add a date when a record is created SQL
  • How to check if a file is empty Python
  • YouTube channel lists – Python DataFrames Python Dataframe

Copyright © 2023 Data Analytics Ireland.

Powered by PressBook Premium theme

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT