Python: Common Elements Between Two Lists

1. Introduction

Finding common elements between two sets of data is a fundamental operation in data analysis. When working with lists in Python, identifying common elements can help in tasks like data filtering, synchronization, and more.

In this blog post, we will learn how to write a Python program to find common elements between two lists.

2. Program Overview

1. Initialize two lists.

2. Use a list comprehension to find common elements.

3. Display the common elements.

3. Code Program

# Python program to find common elements between two lists

# Initializing two lists
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

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

print(f"Common elements: {common_elements}")

Output:

Common elements: [4, 5]

4. Step By Step Explanation

1. We initialize two lists named list1 and list2.

2. We use list comprehension, which is a concise way to create lists. The logic here is to loop through each element in list1 and check if that element also exists in list2.

3. If the element from list1 exists in list2, it's added to the common_elements list.

4. Finally, we display the common elements using the print() function.

Comments