Как сравнить два списка в python

от admin

Как сравнить два списка в Python

В этой статье мы разберемся с различными способами сравнения двух списков в Python. Мы часто сталкиваемся с ситуациями, когда нам нужно сравнить значения элементов данных, хранящихся в любой структуре, например, в списке, кортеже, строке и т.д.

Сравнение – это метод проверки элементов данных одного списка на предмет равенства с элементами данных другого списка.

Методы сравнения двух списков

Мы можем использовать любой из следующих методов для сравнения:

  • Функции reduce() и map().
  • Функция collection.counter().
  • sort() вместе с оператором ==.
  • set() вместе с оператором ==.
  • Функция difference().

1. Функции Python reduce() и map()

Мы можем использовать функцию map() вместе с функцией functools.reduce() для сравнения элементов данных двух списков.

Метод map() принимает в качестве аргументов функцию и итерацию, например список, кортеж, строку и т.д.

Он применяет переданную функцию к каждому элементу итерации, а затем возвращает объект карты, то есть итератор, в качестве результата.

Метод functools.reduce() применяет переданную функцию к каждому элементу итерируемого ввода рекурсивным образом.

Первоначально он применит функцию к первому и второму элементам и вернет результат. Тот же процесс будет продолжаться для каждого из элементов, пока в списке не останется элементов.

Как комбинация, функция map() применяет функцию ввода к каждому элементу, а функция reduce() гарантирует, что она применяет функцию последовательно.

2. Метод Python collection.counter()

Метод collection.counter() можно использовать для эффективного сравнения списков. Функция counter() подсчитывает частоту элементов в списке и сохраняет данные в виде словаря в формате <значение>: <частота>.

Если два списка имеют одинаковый вывод словаря, мы можем сделать вывод, что списки одинаковы.

Примечание. Порядок в списке не влияет на метод counter().

3. Метод Python sort() и оператор ==

Мы можем объединить метод sort() с оператором == для сравнения двух списков.

Метод sort() используется для сортировки входных списков с целью, что если два входных списка равны, то элементы будут находиться в одних и тех же позициях индекса.

Примечание. Порядок в списке не влияет на этот метод, потому что мы будем сортировать списки перед сравнением.

Кроме того, оператор == используется для сравнения списка элемент за элементом.

4. Метод Python set() и оператор ==

Метод set() манипулирует элементами данных итерации до отсортированного набора элементов данных, не принимая во внимание порядок элементов.

Кроме того, оператор == используется для поэлементного сравнения элементов данных списка.

5. Понимание пользовательского списка

Мы можем использовать List в Python для сравнения двух списков.

В приведенном выше коде мы устанавливаем элемент указателя «x» на список l1 и l3. Далее мы проверяем, присутствует ли элемент, на который указывает элемент-указатель, в списках.

How to Compare Two Lists in Python

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Introduction

When programming in, or learning, Python you might need to determine whether two or more lists are equal. When you compare lists for equality, you’re checking whether the lists are the same length and whether each item in the list is equal. Lists of different lengths are never equal.

This article describes how to use the following Python features to compare lists:

  • sort() method or the sorted() function with the == operator
  • set() function with the == operator
  • reduce() and map() functions with the == operator
  • collection.Counter() class with the == operator
  • list comprehension

Using the sort() Method or the sorted() Function to Compare Lists

You can use the sort() method or the sorted() function to sort lists with the purpose of comparing them for equality. The sort() method sorts the list in place, while the sorted() function returns a new list. After sorting, lists that are equal will have the same items in the same index positions. The == operator compares the lists, item by item (element-wise comparison).

The order of the original list items is not important, because the lists are sorted before comparison.

Note: You can sort only lists with items of the same data type.

sort() Method Example

The following example demonstrates how to use the sort() method to sort and compare lists for equality:

The preceding example code sorts each list, compares l1 to l3 and prints the result, and then compares l1 to l2 and prints the result.

sorted() Function Example

The following example demonstrates how use the sorted() function to sort and compare lists for equality:

The preceding example code returns a sorted version of each list, compares l1 to l3 and prints the result, and then compares l1 to l2 and prints the result.

Using the reduce() and map() Functions to Compare Lists

You can use the Python map() function along with the functools.reduce() function to compare the data items of two lists. When you use them in combination, the map() function applies the given function to every element and the reduce() function ensures that it applies the function in a consecutive manner.

The map() function accepts a function and an iterable as arguments. The map() function applies the given function to each item of the iterable and then returns a map object (iterator) as the result.

The functools.reduce() function also accepts a function and an iterable as arguments. The functools.reduce() function applies the given function to every element of the iterable recursively. Initially, functools.reduce() applies the function on the first and the second items and returns the result, and then applies the function on the result and the third item, and continues until the list has no items left.

When you use them in combination, the map() function applies the given function to every element and the reduce() function ensures that it applies the function in a consecutive manner.

The order of the list items is important when you use the reduce() and map() functions. Lists with the same items in different order will not return true when compared for equality. If required, you can sort the lists first.

The following example demonstrates how to use the reduce() and map() functions to compare lists for equality:

The preceding example code compares l1 to l2 and then compares l1 to l3 .

Using the set() Function to Compare Lists

You can use the set() function to create set objects using the given lists and then compare the sets for equality using the == operator.

The order of the original list items is not important, because the == operator returns true when each set contains identical items in any order.

Note: Duplicate list items appear only once in a set.

The following example demonstrates how to create sets from lists and compare the sets for equality:

The preceding example code creates sets a and b from lists l1 and l2 and then compares the sets and prints the result.

Using the collections.Counter() Class to Compare Lists

The collections.Counter() class can be used to compare lists. The counter() function counts the frequency of the items in a list and stores the data as a dictionary object in the format value:frequency . If two lists have the same dictionary output, you can infer that the lists are the same.

The order of the original list items isn’t important when you use the Counter class to compare lists.

The following example demonstrates how to create Counter objects from the given lists and compare them for equality:

The preceding example code creates Counter objects for lists l1 and l2 , compares them, and prints the result. The code repeats for lists l1 and l3 .

Using List Comprehension to Compare Lists

You can use list comprehension to compare two lists. For more information about list comprehensions, refer to Understanding List Comprehensions in Python 3.

The order of the original list items isn’t important when you use list comprehension to compare lists.

The following example demonstrates how to use a list comprehension to compare lists:

The preceding example code sets a pointer element x to the lists l1 and l2 , then checks if the item pointed by the pointer element is present in the lists. If the result, res is an empty list, then you can infer that the lists are equal, since there are no items that appear in only one of the lists.

Conclusion

This article described a few different ways to compare lists for equality in Python. Continue your learning with more Python tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

The Best Ways to Compare Two Lists in Python

The Best Ways to Compare Two Lists in Python

Check if two lists are equal, which elements match, get the difference between two lists, compare lists of dictionaries, list of strings and more!

Play this article

Table of contents

A while ago I wrote a guide on how to compare two dictionaries in Python 3, and how this task is not as simple as it might sound. It turns out comparing two lists in Python is just so tricky as comparing dict s.

The way we’ve been taught to compare two objects in Python is a bit misleading. Most books and tutorials teach object comparison by using either the == or the is operator. In reality, these two operators cover just a small fraction of the most frequent use cases.

  • what if we want to compare a list of floating-point numbers considering a certain tolerance?
  • what if we wish to contrast two lists but ignoring the order in which the elements appear?
  • maybe we need to compare two lists and return the elements that intersect both
  • sometimes we might want to get the difference between two lists
  • what if we have two lists of strings and need to compare them by ignoring the string cases?
  • what if we’re given a list of numpy arrays to compare each other, what can we do?
  • or maybe we have a list of custom objects, or a list of dictionaries.

The list goes on and on, and for all of these use cases using == doesn’t help.

That’s what we are going to see in this article. We’ll learn the best ways of comparing two lists in Python for several use cases where the == operator is not enough.

Comparing if two lists are equal in python

Comparing if two lists are equal in python

The easiest way to compare two lists for equality is to use the == operator. This comparison method works well for simple cases, but as we’ll see later, it doesn’t work with advanced comparisons.

An example of a simple case would be a list of int or str objects.

Pretty simple, right? Unfortunately, the world is complex, and so is production grade code. In the real world, things get complicated really fast. As an illustration, consider the following cases.

Suppose you have a list of floating points that is built dynamically. You can add single elements, or elements derived from a mathematical operation such as 0.1 + 0.1 .

Clearly, floating point arithmetic has its limitations, and sometimes we want to compare two lists but ignore precision errors, or even define some tolerance. For cases like this, the == operator won’t suffice.

Things can get more complicated if the lists have custom objects or objects from other libraries, such as numpy .

Читать:
Как закрыть фрагмент android

You might also like to compare the lists and return the matches. Or maybe compare the two lists and return the differences. Or perhaps you want to compare two lists ignoring the duplicates, or compare a list of dictionaries in Python.

In every single case, using == is not the answer, and that’s what we are going to see next: how to perform complex comparison operations between two lists in Python.

Comparing two lists of float numbers

In the previous section, we saw that floating point arithmetic can cause precision errors. If we have a list of floats and want to compare it with another list, chances are that the == operator won’t help.

Let’s revisit the example from the previous section and see what is the best way of comparing two lists of floats.

As you see, 0.1 + 0.1 + 0.1 = 0.30000000000000004 , which causes the comparison to fail. Now, how can we do better? Is it even possible?

There are a few ways of doing approaching this task. One would be to create our own custom function, that iterates over the elements and compare it one by one using the math.isclose() function.

Fortunately we don’t have to reinvent the wheel. As I showed in the «how to compare two dicts» article, we can use a library called deepdiff for that. This library supports different types of objects and lists are one of them.

The example below starts off by setting up the two lists we want to compare. We then pass it to the deepdiff.DeepDiff constructor which returns the difference. That’s great, the returned value is much more informative than a simple boolean.

Since we want to ignore the precision error, we can set the number of digits AFTER the decimal point to be used in the comparison.

The result is an empty dict, which means the lists are equal. If we try comparing a list with a float number that differs in more than 3 significant digits, the library will return that diff.

For reproducibility, in this article I used the latest version of deepdiff which is 5.6.0 .

Comparing if two lists without order (unordered lists) are equal

Lists in Python are unordered by default. Sometimes we want to compare two lists but treat them as the same as long as they have the same elements—regardless of their order.

There are two ways of doing this:

  • sorting the lists and using the == operator
  • converting them to set s and using the == operator
  • using deepdiff

These first two methods assume the elements can be safely compared using the == operator. This approach doesn’t work for floating-point numbers, and other complex objects, but as we saw in the previous section, we can use deepdiff .

Sorting the lists and using the == operator

comparing two lists in python using the sorted function

You can sort lists in Python in two different ways:

  • using the list.sort() method
  • using the sorted() function

The first method sorts a list in place, and that means your list will be modified. It’s a good idea to not modify a list in place as it can introduce bugs that are hard to detect.

Using sorted is better since it returns a new list and keep the original unmodified.

Let’s see how it works.

As a consequence, by sorting the lists first we ensure that both lists will have the same order, and thus can be compared using the == operator.

Converting the list s to a set

comparing two lists in python using a set

Contrary to lists, sets in Python don’t care about order. For example, a set <1, 2, 3>is the same as <2, 3, 1>. As such, we can use this feature to compare the two lists ignoring the elements’ order.

To do so, we convert each list into a set, then using the == to compare them.

Using the deepdiff library

This library also allows us to ignore the order in sequences such as list s. By default, it will take the order in consideration, but if we set ignore_order to True , then we’re all good. Let’s see this in action.

Using deepdiff has pros and cons. In the end, it is an external library you need to install, so if you can use a set to compare the lists, then stick to it. However, if you have other use cases where it can shine, then I’d go with it.

How to compare two lists and return matches

getting the intersection of two lists in python

In this section, we’ll see how we can compare two lists and find their intersection. In other words, we want to find the values that appear in both.

To do that, we can once more use a set and take their intersection.

How to compare two lists in python and return differences

We can the find difference between two lists in python in two different ways:

  • using set
  • using the deepdiff library

Using set

getting the difference between two lists in python using set

Just like we did to determine the intersection, we can leverage the set data structure to check difference between two lists in python.

If we want to get all the elements that are present in the first list but not in the second, we can use the set.difference() .

On the other hand, if we want to find all the elements that are in either of the lists but not both, then we can use set.symmetric_difference() .

This method has a limitation: it groups what is different between the lists into one final result which is the set difference. What if we want to know which elements in that diff belong to what list?

Using deepdiff

As we’ve seen so far, this library is powerful and it returns a nice diff. Let’s see what happens when we use deepdiff to get the difference between two lists in Python.

Accordingly, deepdiff returns what changed from one list to the other. The right approach then will depend on your use case. If you want a detailed diff, then use DeepDiff . Otherwise, just use a set .

How to compare two lists of strings

Comparing two lists of string in Python depends largely on what type of comparison you want to make. That’s because we can compare a string in a handful of ways.

In this section, we’ll see 3 different ways of doing that.

The simplest one is using a == operator, like we saw in the beginning. This method is suitable if you want a strict comparison between each string.

Things start to get messy if you want to compare the list of strings but ignoring the case. Using the == for that just doesn’t work.

The best tool for that is again deepdiff . It allows us to ignore the string by passing a boolean flag to it.

We can also ignore the order in which the strings appear in the lists.

You can also go further and perform advanced comparisons by passing a custom operator to DeepDiff .

For example, suppose you want to compare the strings but ignoring any whitespace they may have.

Or perhaps you want to perform a fuzzy matching using an edit distance metric.

To do that, we can write the comparison logic in the operator class and pass it to DeepDiff .

In this first example, we’ll ignore any whitespace by trimming the strings before comparing them.

Then we can just plug into DeepDiff by adding it to the list of custom_operators , like so custom_operators=[IgnoreWhitespaceOperator()] .

How to compare two lists of dictionaries

Comparing two lists of dictionaries in Python is definitely intricate without the help of an external library. As we’ve seen so far, deepdiff is versatile enough and we can use it to compare deep complex objects such as lists of dictionaries.

Let’s see what happens when we pass two lists of dictionaries.

It outputs the exact location where the elements differ and what the difference is!

Let’s see another example where a list has a missing element.

It says the the second dictionary has been removed, which is the case for this example.

How to compare two list of lists

Comparing multidimensional lists—a.k.a list of lists—is easy for deepdiff . It works just like a list of dict s.

In the example below, we have two multidimensional lists that we want to compare. When passed to DeepDiff , it returns the exact location in which the elements differ.

For example, for the position [1][0] , the new value is 8, and the old is 3. Another interesting aspect is that it works for deeply nested structures, for instance, deepdiff also highlights the difference in the [2][0][0] position.

When feeding the library with two identical multidimensional lists, it returns an empty response.

How to compare two lists of objects

Sometimes we have a list of custom objects that we want to compare. Maybe we want to get a diff, or just check if they contain the same elements. The solution for this problem couldn’t be different: use deepdiff .

The following example demonstrates the power of this library. We’re going to compare two lists containing a custom objects, and we’ll be able to assert if they are equal or not and what are the differences.

In the example below, we have two lists of Person objects. The only difference between the two is that in the last position Person object has a different age. deepdiff not only finds the right position — [1] — but also finds that age field is different as well.

How to compare two lists of numpy arrays

In this section, we’ll see how to compare two lists of numpy arrays. This is a fairly common task for those who work with data science and/or machine learning.

We saw in the first section that using the == operator doesn’t work well with lists of numpy arrays. Luckily we can use. guess what!? Yes, we can use deepdiff .

The example below shows two lists with different numpy arrays and the library can detect the exact position in which they differ. How cool is that?

Conclusion

In this post, we saw many ways to compare two lists in Python. The best method depends on what kind of elements we have and how we want to compare. Hopefully, you now know how to:

How to compare two lists in python?

Now I want to compare these two lists. I guess split returns a list. We can do simple comparision in Java like dateArr[i] == sdateArr[i] , but how can we do it in Python?

jinawee's user avatar

6 Answers 6

You could always do just:

By casting a , b and c as a set, you remove duplicates and order doesn’t count. Comparing sets is also much faster and more efficient than comparing lists.

PyRsquared's user avatar

If you mean lists, try == :

If you want to compare strings (per your comment):

Given the code you provided in comments, I assume you want to do this:

The split -method of the string returns a list. A list in Python is very different from an array. == in this case does an element-wise comparison of the two lists and returns if all their elements are equal and the number and order of the elements is the same. Read the documentation.

Похожие статьи