📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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
Post a Comment
Leave Comment