Python find list difference

Python How to Find the Difference Between Two Lists

To find the asymmetric difference between two lists in Python:

  1. Convert the lists to sets.
  2. Subtract the sets from one another to find the difference.
  3. Convert the result back to a list.
names1 = ["Alice", "Bob", "Charlie", "David"] names2 = ["Bob", "Charlie"] difference = list(set(names1) - set(names2)) print(difference)

Asymmetric Difference between Lists in Python

The asymmetric difference in set theory means that given sets A and B, return the elements that are in set A but not in set B. But do not return the elements that are in set B but not in A.

This image illustrates the idea:

The example you saw above is about the asymmetric difference between two lists in Python.

names1 = ["Alice", "Bob"] names2 = ["Bob", "Charlie"] difference = list(set(names1) - set(names2)) print(difference)

Even though you might expect [«Alice», «Charlie»] as neither name occurs in both sets. But because the asymmetric difference is about finding only the elements that are in set A but not in B, it only returns “Alice”.

To fix this problem, you need to calculate the symmetric difference between the two lists.

Symmetric Difference between Lists in Python

The symmetric difference in set theory means given sets A and B, return the elements that are in set A but not in set B and vice versa.

To get the symmetric difference between two lists in Python:

  1. Convert the lists to sets.
  2. Use the built-in symmetric_difference() function of sets to get the symmetric difference.
  3. Convert the result back to a list.
names1 = ["Alice", "Bob"] names2 = ["Bob", "Charlie"] difference = list(set(names1).symmetric_difference(set(names2))) print(difference)

Now both names that do not occur in both lists are in the result.

Conclusion

The Asymmetric difference between two lists in Python returns the items that list A has but list B does not. This means if list B has an item that is not found in A, it does not count.

To calculate the asymmetric difference in Python lists:

  1. Convert the lists to sets.
  2. Compute the difference by subtracting one set from the other.
  3. Convert the result to a list.

The symmetric difference between two lists in Python returns the items in list A that are not in list B and vice versa. To calculate the symmetric difference in Python lists:

  1. Convert the lists to sets.
  2. Compute the difference with symmetric_difference() method.
  3. Convert the result to a list.

Thanks for reading. Happy coding!

Further Reading

Источник

Читайте также:  Can we have same id in html

Python List Difference: Find the Difference between 2 Python Lists

Python List Difference Cover Image

In this post, you’ll learn how to find the Python list difference, meaning what items are different between two lists.

In particular, you’ll learn: how to find the difference between lists when order and duplicates matters, when they don’t matter, and how to find the symmetrical difference between two lists.

The Short Answer: Use Set Subtraction

list1 = [1,2,3,4,5,6] list2 = [2,4,5,7] difference = list(set(list1) - set(list2)) print(difference) # Returns [1, 3, 6]

What is Python List Difference?

Python list difference refers to finding the items that exist in one list, but not in the other. There are two main things to understand here:

  1. The comparison ordering matters: if you want to find the items in one list but not in the other, you need to use that are your comparator
  2. Whether repetition matters: since lists can contain duplicate values, some methods will work better for this

Comparison Ordering

Say we have two different lists:

list1 = [1,2,3,4,5,6] list2 = [2,4,5,7] 

If we were to calculate the difference between list1 and list2, we would find that list1 contains [1, 3, 6] , while list2 doesn’t.

If we were to calculate the difference between list2 and list1, we would find that list2 contains [7] , while list1 doesn’t.

If you’re looking to find the list of items that exist in either list but not both, check out the section on finding Python symmetrical difference.

Duplicates in Lists

Now, to understand better, let’s look at three different lists:

list1 = [1,2,3,4,5,6] list1b = [1,2,3,3,4,5,6] list2 = [2,4,5,7]

We have lists list1 and list2 which contain only unique items. However, we also have list1b that contains two 3’s. Were we to calculate a duplicate list difference:

  • Between list1 and list2 , we would return [1,3,6] .
  • However, were we do to the same between list1b and list2 , we would return [1,3,3,6] .

Now, were we to calculate non-repetitve list differences, both differences would simply be [1,3,6] .

Calculate List Difference with Duplicate Items with a For Loop

In order to calculate a repetitive list difference in Python, we can use a for-loop. For a refresher on for-loops, check out my post here and my video tutorial here:

Источник

Difference between Two Lists in Python: 05 Methods (with code)

Difference between Two Lists in Python: 05 Methods (with code)

Lists are one of the most important data structures in Python programming. And one of the important operations on the list is to find the difference between two lists in python. We will learn about different methods to compare lists with examples and code.

What is Python List Difference?

Finding things that are present in one list but absent from the other is known as Python list difference. But remember that the comparison ordering matters. We also need to keep in mind whether we want repetition in the list or not, because the list can have duplicate values.

Before moving forward, let’s understand two types of differences:

  1. Asymmetric difference: It returns the items that list1 has but list2 does not. This means if list2 has an item that is not found in list1, it does not count.
  2. Symmetric difference: It returns the items in list1 that are not in list2 and vice versa.
Читайте также:  Python byte array insert

Let’s now look at a few approaches to find differences between the two lists:

1) Using the Membership Function

In python, as we know we have membership operators ‘in’ and ‘not in’, We can use these operators to differentiate between the elements of a list by passing each list in for loop and implementing an if-else condition on it.

It returns an asymmetric difference between the list that is if given two lists: list1 and list2; your function will return the elements that are in list1 but not in list2. But do not return the elements that are in list2 but not in list1 for that you need to reverse the function and find the output.

You can also use the set() function to remove duplicates from a list and then iterate it using a membership operator.

# Intializing the lists List1 = [4,28,6,99,100,25,18,10,40,73] list2 = [25, 40,73,4,80,63,99,6] new_list1 = [] #empty list for i in List1: if i not in list2: new_list1.append(i) print("elements of list 1 that are not present in list 2 ",new_list1) new_list2 = [] #empty list for i in list2: if i not in List1: new_list2.append(i) print("elements of list 2 that are not present in list 1 ",new_list2)
elements of list 1 that are not present in list 2 [28, 100, 18, 10] elements of list 2 that are not present in list 1 [80, 63]

We can also cut down our coding lines and make our program easier by using list comprehension instead of loops.

You can more clearly understand what’s happening in the above code with the following image:

python list difference example

Here is the new code with list comprehension:

# Intializing the lists list1 = [4,28,6,99,100,25,18,10,40,73] list2 = [25, 40,73,4,80,63,99,6] s = set(list2) # set() function to remove duplicacy new_list1 = [x for x in list1 if x not in s] # List comprehension print("elements of list 1 that are not present in list 2 ",new_list1) s2=set(list1) new_list2 = [x for x in list2 if x not in s2] print("elements of list 2 that are not present in list 1 ",new_list2)
elements of list 1 that are not present in list 2 [28, 100, 18, 10] elements of list 2 that are not present in list 1 [80, 63]

2) Without using the set() function

In this approach, we don’t use any pre-built function like set(). We simply concatenate a given two lists and iterate a loop over it to check its element’s presence in both lists individually and all common elements are removed.

Hence, storing all distinct elements of both lists in a new one. It is a symmetric difference approach to the solution.

# Python code to get difference of two lists # Not using set() def Diff(list1, list2): li_dif = [i for i in list1 + list2 if i not in list1 or i not in list2] return li_dif # Driver Code list1 = [4,28,6,99,100,25,18,10,40,73] list2 = [25, 40,73,4,80,63,99,6] list3 = Diff(list1, list2) print("All different elements of two given list",list3)
All different elements of two given list [28, 100, 18, 10, 80, 63]

3) Using Numpy functions

NumPy is an open-source Python library that’s used in almost every field of science and engineering. It is used for working with multidimensional and single-dimensional array elements. It also has functions for working in the domain of linear algebra, Fourier transform, and matrices. The array object in NumPy is called ndarray.

We have so many in-built functions and out of these all functions we have concatenate(arr1,arr2) which merges two lists, and setdiff1d(arr1,arr2,assume_unique=False) which helps us to differentiate between the list i.e. It returns the ndarray which stores the unique values of arr1 which are not in arr2.

import numpy as np list1 = [4,28,6,99,100,25,18,10,40,73] list2 = [25, 40,73,4,80,63,99,6] dif_1_2 = np.setdiff1d(list1, list2) dif_2_1 = np.setdiff1d(list2, list1) new_list = [np.concatenate((dif_1_2, dif_2_1))] print("All different elements of two given list",new_list)
All different elements of two given list [array([ 10, 18, 28, 100, 63, 80])]

4) Using symmetric_difference()

The elements that are either in the first set or the second set are returned using the symmetric_difference() technique. Unlike the shared items of the two sets, the intersection is not returned by this technique.

list1 = [4,28,6,99,100,25,18,10,40,73] list2 = [25, 40,73,4,80,63,99,6] set_dif = [set(list1).symmetric_difference(set(list2))] print(set_dif)

5) Basic method

In this approach, we find the set of each list and differentiate it from another set. This is the easiest method as it does not require any pre-built function use. First, we convert the list into a set. Second, we will subtract the sets from one another to find the difference. Last, we convert the result back to a list.

list1 = [4,28,6,99,100,25,18,10,40,73] list2 = [25, 40,73,4,80,63,99,6] new_list1=set(list1)-set(list2) new_list2=set(list2)-set(list1) print("set of elements of list 1 that are not present in list 2 ",new_list1) print("set of elements of list 2 that are not present in list 1 ",new_list2)
set of elements of list 1 that are not present in list 2 10, 18, 100, 28> set of elements of list 2 that are not present in list 1 80, 63>

Conclusion

Today, we learned how to find the difference between two lists in python. If you still have any queries, we can connect you with our expert for python assignment help online anytime. Happy learning 🙂

Читайте также:  Python json list index

Источник

Оцените статью