Python: Difference Between Lists

📘 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

In programming, it's common to encounter scenarios where you need to find the difference between two lists. This blog post will guide you through a Python program that accomplishes this task.

2. Program Overview

1. Define two lists.

2. Use set operations to find the difference between the two lists.

3. Display the differences.

3. Code Program

# Python program to find the difference between two lists

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

# Find the difference between the two lists
difference1 = list(set(list1) - set(list2))
difference2 = list(set(list2) - set(list1))

# Combine the differences
combined_difference = difference1 + difference2

# Print the differences
print("Difference between list1 and list2:", combined_difference)

Output:

Difference between list1 and list2: [1, 2, 3, 6, 7, 8]

4. Step By Step Explanation

1. We begin by defining two lists, list1 and list2.

2. To find the items that are in list1 but not in list2, we convert both lists to sets and use the subtraction operation. We do the same to find items in list2 that aren't in list1.

3. We then combine the differences from both operations to get all distinct items.

4. Finally, we print out the combined difference. As observed in the output, the numbers 1, 2, and 3 are in list1 but not in list2, while 6, 7, and 8 are in list2 but not in list1.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare