Python list comprehension compare two lists

Python doesnt have a direct method to compare a list. But there are multiple ways to compare the two lists of strings in python.

The following methods to perform List comparison:

  • reduce() and map() functions
  • collection.counter() method
  • sort() method and == operator
  • set() method and == operator
  • Custom List Comprehension

Note: The cmp() function doesnt use in Python 3.x version.

Python compare two lists of strings example

Simple example code with all possible ways.

Use reduce() and map() functions

import functools list1 = ['A', 'B', 'C'] list2 = ['A', 'D', 'E'] if functools.reduce(lambda x, y: x and y, map(lambda a, b: a == b, list1, list2), True): print("Both List are same") else: print("Not same")

Output:

Python list comprehension compare two lists

Python collection.counter() method

The counter() function counts the frequency of the items in a list and stores the data as a dictionary in the format <value>:<frequency>.

import collections list1 = ['A', 'B', 'C'] list2 = ['A', 'D', 'E'] if collections.Counter(list1) == collections.Counter(list2): print("Both List are same") else: print("Not the same")

Output: Not the same

Use sort() method and == operator to compare lists

The sorted list and the == operator are used to compare the list, element by element.

list1 = ['A', 'B', 'C'] list2 = ['A', 'C', 'B'] list1.sort() list2.sort() if list1 == list2: print("Both List are the same") else: print("Not same")

Output: Both List are the same

Python set() method and == operator to compare two lists

Equal == operator is used for comparison of the data items of the list in an element-wise fashion.

list1 = ['A', 'B', 'C'] list2 = ['A', 'C', 'B'] s1 = set(list1) s2 = set(list2) if s1 == s2: print("Both List are the same") else: print("Not same")

Output: Both List are the same

Use Custom List Comprehension to Compare Two Lists

If the string list same then the list has zero elements.

list1 = ['A', 'B', 'C'] list2 = ['A', 'C', 'B'] res = [x for x in list1 + list2 if x not in list1 or x not in list2] print(res)

Output: []

Do comment if you have any doubts and suggestions on this Python list topic code.

Note: IDE:PyCharm2021.3 (Community Edition)

Windows 10

Python 3.10.1

AllPython Examplesare inPython3, so Maybe its different from python 2 or upgraded versions.

Python list comprehension compare two lists

Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.

Share this:

  • Facebook
  • WhatsApp
  • LinkedIn
  • More
  • Twitter
  • Print
  • Reddit
  • Tumblr
  • Pinterest
  • Pocket
  • Telegram
  • Skype
  • Email

Related