How to compare two lists in Python?

devquora
devquora

Posted On: Feb 22, 2018

 

There are multiple ways to compare 2 lists in Python and check they are Identical or not. Here we are going to use sum() + zip() + len() to perform this check.

  
# initializing our lists  
list1 = [1, 2, 4, 3, 5] 
list2 = [1, 2, 4, 3, 6] 
  
# printing lists 
print ("The first list is : " + str(list1)) 
print ("The second list is : " + str(list2))
# using sum() + zip() + len() to check if # lists are equal if len(list1)== len(list2) and len(list1) == sum([1 for i, j in zip(list1, list2) if i == j]):
print ("The lists are identical") else : print ("The lists are not identical")

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    Python Interview Questions

     How is Python different from Java?

    Java and Python differ in typing, syntax, and speed, but both are valuable for developers. Java uses static typing and braces for blocks, while Python uses dynamic typing and indentation. Python is ge..

    Python Interview Questions

    How does exception handling in Python differ from Java?

    Python’s try-except block allows for effective exception handling, enabling programmers to catch and handle errors without ending the program. This technique ensures that errors can be managed grace..

    Python Interview Questions

    What is a module and package in Python?

    Python modules are ".py" files with classes, functions, and variables. Packages are directories containing modules and sub-packages, marked by an init.py file. This file can be empty but indicates the..