HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat N Strings
      • Python Example Code to Concat 2 Numbers
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
    • Modules and Libraries
      • Python Code to Load .SO File (and Invoke a Function)
      • Python Code for Automation using BDD
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

Python Example Code to Remove Duplicates from a List

When working with lists in Python, duplicate values can sometimes be a problem. There are several ways to remove these duplicates, depending on whether you need to preserve the order of the elements or not.

We will discuss two common methods to achieve this: using a set and using a list comprehension.

Method 1: Using a Set

# Method 1: Using a Set

def remove_duplicates_with_set(lst):
    return list(set(lst))

# Example usage
original_list = [1, 2, 2, 3, 4, 4, 5]
result_list = remove_duplicates_with_set(original_list)
print("Original list:", original_list)
print("List after removing duplicates:", result_list)

Output:

Original list: [1, 2, 2, 3, 4, 4, 5]
List after removing duplicates: [1, 2, 3, 4, 5]

In Python, a set is a built-in data structure that automatically ensures all elements are unique. This makes it a convenient tool for removing duplicates from a list.

How it Works

  • Convert List to Set: When you convert a list to a set using set(lst), any duplicate elements in the list are automatically removed. This is because sets do not allow duplicate values.
  • Convert Back to List: After the conversion, you typically need to convert the set back to a list if you need the result in list format. This is done using list(set(lst)).

Example:

Suppose you have a list [1, 2, 2, 3, 4, 4, 5]. Converting this list to a set removes the duplicates, resulting in {1, 2, 3, 4, 5}. Converting it back to a list gives [1, 2, 3, 4, 5].

Considerations

  • Order Not Preserved: One drawback of this method is that it does not preserve the original order of the elements. The resulting list might have its elements in a different order than the original list.

Method 2: Using a List Comprehension

# Method 2: Using a List Comprehension

def remove_duplicates_with_list_comprehension(lst):
    seen = set()
    return [x for x in lst if not (x in seen or seen.add(x))]

# Example usage
original_list = [1, 2, 2, 3, 4, 4, 5]
result_list = remove_duplicates_with_list_comprehension(original_list)
print("Original list:", original_list)
print("List after removing duplicates:", result_list)

Output:

Original list: [1, 2, 2, 3, 4, 4, 5]
List after removing duplicates: [1, 2, 3, 4, 5]

This method combines a list comprehension with a set to remove duplicates while maintaining the order of elements. It is particularly useful when the order of elements matters.

How it Works

  • Initialize an Empty Set: A set called seen is used to keep track of elements that have already been encountered.
  • List Comprehension: The list comprehension iterates over each element of the original list. For each element, it checks if it is not in the seen set. If the element is not in the set, it is added to the result list, and also added to the seen set to ensure it is not added again.

Example

Consider the list [1, 2, 2, 3, 4, 4, 5]. As you iterate through the list:

1 is added to the result list and the seen set.

2 is added to the result list and the seen set.

The second 2 is ignored because it is already in the seen set.

This process continues for all elements, resulting in the list [1, 2, 3, 4, 5].

Considerations

  • Order Preserved: This method preserves the order of the first occurrence of each element in the original list.
  • Efficiency: It is efficient in terms of time complexity, as checking membership in a set and adding elements are both average O(1) operations.

Both methods are effective for removing duplicates, and the choice between them depends on whether preserving the original order is important to your application.

Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Example Python Code to interact with databases using libraries like SQLAlchemy
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Python Code to Perform Data Analysis with Pandas
  • Example Python Code to Plot Data Using Matplotlib

No luck finding what you need? Contact Us

Previously
Python Code to Find Difference Between 2 Strings
Up Next
Python Example Code to Calculate Height of Triangle
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2025 Happiom. All Rights Reserved.