How to compare lists in Python

In this post, we will see how to compare lists in Python.

Python compare lists

Lists in Python are mutable and can store a finite number of elements. We cannot determine whether a list is greater or less than any other list based on general criteria. So when we talk about comparing lists, we mean checking whether two lists have the same elements or not.

How to compare lists in Python

In this article, several ways are discussed to compare two lists in Python. Two lists can only be equal if they are of the same length so in this article all examples assume that the lists being compared are of the same length.

Using the sort() function and == operator

We can use the equality operator (==) to compare two lists and check whether they are equal or not. It is advisable to use the sort() function before comparing because sometimes the lists may contain the same elements but they might be shuffled. The sort() function will sort them. Also, this function sorts the original list and does not create a new list.

See the code below.

Output:

True
False

In the above example,

  • We created three lists a, b, and c.
  • We sorted the lists and compared them.
  • Lists a and b were equal and True is returned.
  • Lists a and c were not equal so we get False.
  • The sort() function can be used with any of the methods discussed below.

Using the map() and reduce() functions

We can implement a simple lambda function to compare two lists. Such functions are used to implement simple, one-line logic.

For this, we will use the map() and reduce() functions. The map() function takes an iterable and applies a function to every element of this object. The reduce() function will be applied to the map object to compare the two elements.

It is necessary to sort the lists before using these functions.

We implement the above logic in the following code snippet.

Output:

Equal

Using the set() function and == operator

The set() function returns a set object that is unordered and contains distinct elements. We can compare these sets using the == operator.

There is no requirement to sort these lists a set is unordered.

For example,

Output:

True
False

In the above code,

  • We first created three lists.
  • These lists were converted to sets using the set() function.
  • These sets were compared for equality using the == operator.

Using the for loop

We can use the for loop to iterate over both lists and compare each element individually. If even a single pair of elements do not match, we break out of the loop and know that the lists are not equal.

See the code below.

Output:

Equal

Using the set() function and - operator

We can convert two lists to a set using the set() function and calculate their difference. The difference between two the sets is the total elements present in the first set and not in the second set. We can use this difference to compare the two lists. If the difference is an empty set, they are equal, else they are not.

See the following example.

Output:

Equal

Using the collections.Counter() class and == operator

The Counter is a sub-class from the collections module that stores elements in a hashable object with a dictionary-like structure. We can store two lists in such objects and compare them using the == operator.

No requirement to sort the lists beforehand.

For example,

Output:

True

Using the zip(), sum(), and len() functions

The zip() function returns a zip-type object by combining elements of two iterables. The len() function calculates the length of the iterable.

We can use these functions with the sum() function to calculate the total number of indexes where the elements are different. If this sum is 0, then the lists are equal, else they are not equal. It is essential to sort the lists before using these functions.

We implement this logic in the following code snippet.

Output:

Equal

Using the cmp() function

The cmp() function returns 1,-1, and 0 based on the comparison between two integers. We can use it with lists, and if the result is 0 then the two lists are equal.

This function works only in Python 2.

For example,

Output:

Equal

Conclusion

In this article, we discussed different ways to compare two lists in Python. The == operator is used in many methods, and we discovered some innovative ways to achieve the same using sets, cmp(), and zip() methods.


import_contacts

You may also like:

Related Posts

  • Python List of dictionaries
    09 December

    List of Dictionaries in Python

    Table of ContentsHow to Create a List of Dictionaries in Python?How to Access Elements of a List of Dictionaries?Search in a List of Dictionaries in PythonUpdate Values in a List of Dictionaries in PythonHow to Sort List of Dictionaries in Python?Conclusion We use both lists and dictionaries in our python programs. Lists are used to […]

  • Python sort list of lists
    17 November

    Sort List of Lists in Python

    Table of ContentsSort List of Lists Using the sort() Method in PythonUsing the itemgetter() methodUsing Lambda FunctionsSort List of Lists Using the sorted() Function in PythonSort lists of lists on the basis of the length of the inner listsConclusion Several times we use 2-D lists or lists of lists in our programs to represent a […]

  • Remove nan from list in Python
    16 November

    Remove nan From List In Python?

    Table of ContentsWhat is nan in python?How to remove nan from list in python?Remove nan from list using the str() functionRemove nan from list using math.isnan() functionRemove nan from list using numPy.isnan() functionRemove nan from list using pandas.isnull() functionConclusion In python, nan is a special value used to represent missing values. In this article, we […]

  • List intersection in Python
    11 November

    List intersection in python

    Table of ContentsWhat is the list intersection in Python?Ways to find the list intersection in PythonUsing the for loop to achieve list intersection in PythonUsing the set() function to find list intersection in PythonUsing the intersection() function to find list intersection in PythonUsing the filter() and lambda functions to find list intersection in PythonUsing the […]

  • Initialize list with zeros in Python
    25 October

    Four Ways To Initialize List With Zeros In Python

    Table of ContentsWhy Initialize List with Zeros in Python?How Can We Initialize List With Zeros In Python?Initialize List With Zeros Using * Operator In PythonInitialize List With Zeros Using  itertools.repeat() FunctionInitialize List With Zeros Using  Generator Comprehension In PythonInitialize List With Zeros Using  List Comprehension In PythonConclusion Lists in Python are one of the most […]

  • 06 October

    How to find index of all occurrences in list in Python

    Table of ContentsThe easiest method – Using list count() methodThe Basic Method – Using for loopsThe shortest method – Using the enumerate() functionThe fastest method – Using a numpy arrayUsing itertools moduleUsing more-itertools LibraryUsing index() function List is a data type in Python. It is used to store multiple values in one variable. If you […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.