Applying the Technique to Identify Duplicates
Now that you understand the concept of comparing list and set lengths to detect duplicates, let's apply this technique to some real-world examples.
Example 1: Identifying Duplicates in a List of Names
Suppose you have a list of names, and you want to find out if there are any duplicate names.
names = ["John", "Jane", "Bob", "Alice", "John", "Bob"]
names_set = set(names)
print(f"Length of the list: {len(names)}")
print(f"Length of the set: {len(names_set)}")
if len(names) > len(names_set):
print("The list contains duplicate names.")
duplicate_names = [name for name in names if names.count(name) > 1]
print("Duplicate names:", duplicate_names)
else:
print("The list does not contain any duplicate names.")
Output:
Length of the list: 6
Length of the set: 4
The list contains duplicate names.
Duplicate names: ['John', 'Bob']
In this example, the length of the names
list is 6, while the length of the names_set
is 4, indicating that the list contains duplicate names. The code then identifies the duplicate names and prints them out.
Example 2: Removing Duplicates from a List
You can also use this technique to remove duplicates from a list and create a new list with unique elements.
original_list = [1, 2, 3, 2, 4, 1, 5]
unique_list = list(set(original_list))
print("Original list:", original_list)
print("Unique list:", unique_list)
Output:
Original list: [1, 2, 3, 2, 4, 1, 5]
Unique list: [1, 2, 3, 4, 5]
In this example, we convert the original_list
to a set to remove the duplicates, and then convert the set back to a list to create the unique_list
.
By understanding and applying this simple technique, you can effectively identify and handle duplicate elements in your Python lists, making your code more robust and efficient.