Removing duplicates from a list is a common task in Python programming. In this blog post, we’ll explore different code examples that demonstrate how to remove duplicates from a list efficiently.
Example 1:
numbers = [1, 2, 2, 3, 4, 4, 5] unique_numbers = list(set(numbers)) print(unique_numbers)
Output: [1, 2, 3, 4, 5]
Example 2:
fruits = ['apple', 'banana', 'orange', 'banana', 'kiwi', 'apple'] unique_fruits = [] for fruit in fruits: if fruit not in unique_fruits: unique_fruits.append(fruit) print(unique_fruits)
Output: [‘apple’, ‘banana’, ‘orange’, ‘kiwi’]