. Advertisement .
. Advertisement .
Asserting the equality of lists in Python is one of the most common ways to check the equality of lists. However, Python provides other options that allow us to make sure that the two lists are the same. In this post, we will introduce popular methods for “Checking List Equality In Python“.
How Can You Check List Equality In Python?
Option 1: Utilize == operator
You can examine if both lists are the same by utilizing the == operator. Let’s take a look at an example of this:
l1 = [11,12,13,14,15] l2 = [12,1,8,15,14,8] l3 = [11,12,13,14,15] print(l1 == l2) print(l1 == l3)
Option 2: Utilize == and numpy.all()
You can examine if both lists are the same by using == and numpy.all(). Let’s take a look at an example of this:
import numpy as np l1 = [11,12,13,14,15] l2 = [12,1,8,15,14,8] l3 = [11,12,13,14,15] print((np.array(l1) == np.array(l2))) print((np.array(l1) == np.array(l3)))
False [ True True True True True]
Option 3: Utilize list.sort() and == operator
Excepting two options mentioned above, there is another option for you to check list equality in Python.It is utilizinglist.sort()and==operator.
This process can be accomplished using the == operator and sort(). You sort the list first so that all elements are in the same position if the two lists are identical. However, this does not account for the list’s element order. Look at this example:
# Python 3 code to demonstrate # check if list are identical # using sort() + == operator # initializing lists test_list1 = [1, 2, 4, 3, 5] test_list2 = [1, 2, 4, 3, 5] # printing lists print ("The first list is : " + str(test_list1)) print ("The second list is : " + str(test_list2)) # sorting both the lists test_list1.sort() test_list2.sort() # using == to check if # lists are equal if test_list1 == test_list2: print ("The lists are identical") else : print ("The lists are not identical")
The first list is : [1, 2, 4, 3, 5] The second list is : [1, 2, 4, 3, 5] The lists are identical
This solution is very simple and easy, isn’t it? However, it works flawlessly for you. It will make your error completely disappear and your program will run well without any errors. So, what are you waiting without applying it? Let’s try it to get your desired results.
We hope you will enjoy our blog post on “Checking List Equality In Python“. Please leave a comment if you have any further questions or concerns regarding installing pip on your machine. Thank you for taking the time to read; we are always delighted anytime one of our pieces can give important information on this topic!