Compare Two Lists of Strings in Python (5 Examples)


This tutorial shows how to find similarities and dissimilarities between two string lists in Python programming.

The article consists of five examples explaning string list comparison. To be more specific, the content of the article looks as follows:

Here’s how to do it!


Example Data

To start with, we’ll need to construct some data that we can use in the following examples:

list1 = ["apple", "banana", "cherry"]                             # create first sample list
list2 = ["apple", "cherry", "banana"]                             # create second sample list
list3 = ["blueberry", "peach", "banana"]                          # create third sample list

As seen, we have created three string lists list1, list2 and list3. Next, we will compare a pair of these lists!


Example 1: Check if Two Lists are Exactly Same

This example shows how to check if two lists are identical. As it will be seen soon, an if-else statement is used to make this comparison.

if list1 == list2:                                                # test if identical
    print("The lists are the same!")
    print("The lists are different!")
# The lists are different!

The if statement has checked if list1 and list2 are identical, if not, the code within the else block is executed.

We have successfully check if two lists are identical, but one might also be interested in if two lists have the same items only, instead of checking an exact similarity. In such a case, the following example can be employed.


Example 2: Check if Two Lists Have Same Element

In this example, we use both if-else statements and the sorted() function to sort lists to be compared before the comparison.

if sorted(list1) == sorted(list2):                                # test if contain same elements
    print("The lists have the same elements!")
    print("The lists have different elements!")
# The lists have the same elements!

This comparison checks if the sorted string lists list1 and list2 are the same. If they are the same after sorting, then it can be concluded that the original lists contain the same elements although they are not necessarily in the same order.

Here, The lists have the same elements! is returned. However, if it was not the case, a further test might be needed to check the common elements. Let’s see how it is performed!


Example 3: Find Common Elements between Two Lists

In this example, I will show how to detect the common elements between two string lists. We need to use Python sets in order to do that. They will enable us to remove the duplicates and use necessary operators, e.g., &.

common_strings = set(list2) & set(list3)                           # store common elements
print("Common strings:", common_strings)                           # print common elements
# Common strings: {'banana'}

Above, we found out that the common element between list2 and list3 is banana.

If you want to obtain the result as a list then using list comprehension can be a better option. Let’s take a look at that!

common_strings = [s for s in list2 if s in list3]                  # store common elements
print("Common strings:", common_strings)                           # print common elements
# Common strings: ['banana']

In the previous code snippet, we have used the list comprehension listing the intersecting items between list2 and list3.

What if we want to find the unique elements? It is performed in a very similar manner. Check out the next example!


Example 4: Find Unique Elements between Two Lists

To find the unique elements, we will use the sets again. But this time we need the substraction operator to find the difference between two sets.

unique_in_list2 = set(list2) - set(list3)                           # store unique elements in list2
print("Strings in list2 but not in list3:", unique_in_list2)        # print unique elements in list2
# Strings in list2 but not in list3: {'cherry', 'apple'}
unique_in_list3 = set(list3) - set(list2)                           # store unique elements in list3
print("Strings in list3 but not in list2", unique_in_list3)         # print unique elements in list3
# Strings in list3 but not in list2 {'blueberry', 'peach'}

It is very intuitive, isn’t it? If you want to obtain a list output then you can use list comprehension directly as follows.

diff_strings = [s for s in list3 if s not in list2]                 # store unique elements in list3
print("Strings in list3 but not in list2:", diff_strings)           # print unique elements in list3
# Strings in list3 but not in list2: ['blueberry', 'peach']

Well done! Needless to say, you can also count the number of common/unique elements. Let’s check it in practice how the common element count is calculated!


Example 5: Find Count of Common Elements between Two Lists

Example 5 illustrates how to find the number of common elements. We can simply call the len() function to find the length of object stored under the name common_strings.

cc_strings= len(common_strings)                            # store common strings
print("Count of Common Elements:", cc_strings)             # print common element count
# Count of Common Elements: 1

As expected value 1 is returned for common_strings. Cool!


Video & Further Resources

Some time ago I have released a video on my YouTube channel, which shows the Python codes of this tutorial. You can find the video below:


The YouTube video will be added soon.


In addition, you may want to have a look at the other tutorials which I have published on my website. Some articles are shown below.


In this tutorial, I have demonstrated how to compare two string lists in the Python programming language. Tell me about it in the comments, if you have additional questions.


Cansu Kebabci R Programmer & Data Scientist

This page was created in collaboration with Cansu Kebabci. Have a look at Cansu’s author page to get more information about her professional background, a list of all his tutorials, as well as an overview on her other tasks on Statistics Globe.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.