Understanding How to Compare Two Lists in Python
- Last modified: 15 December 2010
- Category: python tutorial
In this post, we going compare two lists with different methods.
Method 1: Comparison between two lists by using python condition.
in this example, we'll check if two lists are equal
a = [1, 2, 3, 4]
b = [1, 2, 3, 5]
if a == b :
print('YES! NO! list "a" and list "b" are similar')
else:
print('NO! list "a" and list "b" are not similar')
Output:
NO! list a and list b are not similar
method 2: Comparison between two lists using sets module
in this example, we will compare between list "a" and "b" and getting duplicate items
So let's do it
a = [1, 2, 3, 4]
b = [1, 2, 3, 5]
print(set(a) & set(b))
Output:
{1, 2, 3}
for more information check out sets module documentation sets module documentation
English today is not an art to be mastered it's just a tool to use to get a result