To compare two lists in Python is easy with build in functions or list comprehensions. The more difficult problems is to compare two lists case insensitive. In this article you can find 3 examples. The first example is finding the missing elements between two list without taking into account the case of the words:
countries1 = ['Brazil', 'Italy', 'Egypt', 'Canada', 'China', 'Panama', 'Mexico']
countries2 = ['Cuba', 'Brazil', 'ItalY', 'Egypt', 'canada', 'China', 'Australia']
missing = []
d = [x.lower() for x in countries1]
for m in countries2:
if m.lower() not in d:
missing.append(m)
print(missing)
result:
['Cuba', 'Australia']
The second example shows how to find the intersection of the two lists case insensitive:
countries1 = ['Brazil', 'Italy', 'Egypt', 'Canada', 'China', 'Panama', 'Mexico']
countries2 = ['Cuba', 'Brazil', 'ItalY', 'Egypt', 'canada', 'China', 'Australia']
missing = []
d = [x.lower() for x in countries1]
for m in countries2:
if m.lower() in d:
missing.append(m)
print(missing)
result:
['Brazil', 'ItalY', 'Egypt', 'canada', 'China']
The last example do the same: case-insensitive comparison of two lists but this time using dictionaries in order to show the matches between the two lists as a couples:
countries1 = ['Brazil', 'Italy', 'Egypt', 'Canada', 'China', 'Panama', 'Mexico']
countries2 = ['Cuba', 'Brazil', 'ItalY', 'Egypt', 'canada', 'China', 'Australia']
d1 = {v.lower(): v for v in countries1}
d2 = {v.lower(): v for v in countries2}
k1 = set(d1.keys())
k2 = set(d2.keys())
common_keys = set(k1).intersection(set(k2))
for key in common_keys:
if d1[key] != d2[key] :
print (key + ":" + str(d2[key]) + " match " + str(d1[key]))
the result is:
italy:ItalY match Italy
canada:canada match Canada
This way you can see the full comparison of two list in Python without taking into account the case of the strings.