Simplest ways to compare two lists of strings in python

This tutorial will discuss comparing two lists of strings in python.

However, at the end of this article, you'll learn the Simplest way to:

  • Check if the two lists are similar
  • Get the duplicated item in two lists
  • Get the unique items in two lists

Check if the two lists are similar

To check if the two lists are similar, use the == operator.

If both lists are similar, it returns True. Otherwise, it returns False.

Example:

# Lists
list_1 = ['a', 'b', 'c']
list_2 = ['q', 's', 'c']

# Check if both lists are similar
print(list_1 == list_2)

Output:

False

Let's see how to use it with the if statement:

# Lists
list_1 = ['a', 'b', 'c']
list_2 = ['q', 's', 'c']

# Check if both lists are similar
if list_1 == list_2:
    print(True)
else:
    print(False)

Output:

False

Get the duplicated item of two lists

There are many ways to get duplicated items in two lists, but we'll focus on the simple way in the following example.

 Let's see an example:

# Lists
list_1 = ['a', 'b', 'c']
list_2 = ['q', 's', 'c']

# Duplicated Items
duplicated = [i for i in list_1 if i in list_2]

# Output
print(duplicated)

Output:

[c]

How the program works:

  1. Iterate over list_1
  2. Check if list_1's items exist on list_2
  3. Append to a new list if so

If the above example is hard to understand, we can use the standard syntax:

# Lists
list_1 = ['a', 'b', 'c']
list_2 = ['q', 's', 'c']

new_list = []
# Iterate Over list_1
for i in list_1:
    # Check if item exist on list_2
    if i in list_2:
        # Append to new_list
        new_list.append(i)

# Print new_list
print(new_list)

Output:

['c']

Get the unique items of two lists

Unique items mean items that are not duplicated in both lists.

We'll use the same method as the duplicated example to get the unique items.

# Lists
list_1 = ['a', 'b', 'c']
list_2 = ['q', 's', 'c']

# Get the unique items
unique = [i for i in list_1 if i not in list_2]

# Output
print(unique)

Output:

['a', 'b']

We've used not in operator to check if list_1's items do not exist in list_2.
For more information about python operators, I recommend you visit Python Operators.

We can also use the set() function to get unique items.

Example:

# Lists
list_1 = ['a', 'b', 'c']
list_2 = ['q', 's', 'c']

# Get the unique items
unique = set(list_1) - set(list_2)

# Output
print(unique)

Output:

{'a', 'b'}

As you can see, we got the result as a set. To convert Set to List, follow the example below.

# Convert to list
print(list(unique))

Output:

['b', 'a']