Python Code Example: Removing Duplicates from a List

In this Python tutorial, we will learn how to remove duplicate elements from a list. Lists in Python can contain repeated elements, and in many cases, we may want to remove these duplicates to ensure that each element appears only once. There are several ways to remove duplicates from a list, such as using sets or list comprehensions. In this tutorial, we will explore these methods and demonstrate how to effectively remove duplicates.

Code Example

# List with duplicate elements
numbers = [10, 20, 20, 30, 40, 10, 50, 60, 50]

# Method 1: Using a set
unique_numbers_1 = list(set(numbers))

# Method 2: Using a list comprehension
unique_numbers_2 = []
[unique_numbers_2.append(num) for num in numbers if num not in unique_numbers_2]

# Output the results
print("Unique numbers using set:", unique_numbers_1)
print("Unique numbers using list comprehension:", unique_numbers_2)

Output

Unique numbers using set: [10, 20, 30, 40, 50, 60]
Unique numbers using list comprehension: [10, 20, 30, 40, 50, 60]

Code Explanation

  1. List with Duplicates: We start with a list numbers = [10, 20, 20, 30, 40, 10, 50, 60, 50] that contains several duplicate values.
  2. Method 1 – Using a Set:
    • A set in Python is an unordered collection of unique elements. When we convert the list to a set using set(numbers), all duplicates are automatically removed because sets do not allow duplicate values.
    • We then convert the set back to a list using list(), resulting in unique_numbers_1, a list without duplicates. However, note that the order of elements may not be preserved since sets are unordered.
  3. Method 2 – Using List Comprehension:
    • This method uses a list comprehension to iterate over each element in the list and add it to a new list (unique_numbers_2) only if it has not already been added.
    • This ensures that only unique elements are added to unique_numbers_2, and the original order of elements is preserved.
  4. Output: We print the results of both methods. The first method (using a set) may not preserve the original order of elements, while the second method (using list comprehension) keeps the original order intact.

This code demonstrates two common methods to remove duplicates from a list: using sets and using list comprehensions. Depending on the specific requirements (such as order preservation), either method can be used effectively to eliminate duplicate values from a list.