Python doesnt have a direct method to compare a list. But there are multiple ways to compare the two lists of strings in python. Show The following methods to perform List comparison:
Note: The cmp() function doesnt use in Python 3.x version. Python compare two lists of strings exampleSimple example code with all possible ways. Use reduce() and map() functionsimport 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 collection.counter() methodThe 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 listsThe 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 listsEqual == 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 ListsIf 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.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical. Share this:
Related |