Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to compare two lists in Python

Understanding List Comparison in Python

The Basics of Lists

Imagine a shopping list. It contains everything you need to buy from the supermarket. In the world of Python, this is exactly what a list is. It’s a collection of items, which can be numbers, strings, or even other lists. This is how you create a list in Python.

shopping_list = ["eggs", "milk", "bread", "butter"]

Why Compare Lists?

You may ask, why do we need to compare lists in Python? Let's use an example to illustrate. Suppose you have two shopping lists. One is your regular shopping list and the other is a list of items on sale at the supermarket. You would want to compare these two lists to find out which items on your regular list are on sale. This is where list comparison comes in handy.

Comparing Lists for Equality

Let's say we have two lists of numbers, and we want to check if they are identical. We can do this using the equality operator (==).

list1 = [1, 2, 3, 4, 5]
list2 = [1, 2, 3, 4, 5]

print(list1 == list2)  # This will output: True

Comparing Lists for Difference

Sometimes, we would want to find the differences between two lists. For example, what items are in list1 that are not in list2, and vice versa. This can be done using sets in Python.

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

diff_list1_list2 = list(set(list1) - set(list2))
diff_list2_list1 = list(set(list2) - set(list1))

print(diff_list1_list2)  # This will output: [1, 2, 3]
print(diff_list2_list1)  # This will output: [8, 6, 7]

Finding Common Elements in Lists

Just like finding differences, we can also find the common elements in two lists. This is like finding out which items on your regular shopping list are on sale at the supermarket.

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

common_elements = list(set(list1) & set(list2))

print(common_elements)  # This will output: [4, 5]

List Comparison with List Comprehension

Python also provides a powerful feature known as list comprehension that allows us to create new lists based on existing ones. It can also be used to compare lists.

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

# Using list comprehension to find common elements
common_elements = [i for i in list1 if i in list2]

print(common_elements)  # This will output: [4, 5]

Conclusion

Comparing lists in Python is like sorting out your shopping list. Whether you're checking if two lists are identical, finding the differences, or identifying the common items, Python has got you covered. The next time you're faced with a task involving list comparison, don't hesitate to put these methods into practice. Remember, just like in shopping, the goal is efficiency and getting the best out of what you have!