Python Remove Duplicate Elements from a List
Page Info
Content

Python Remove Duplicate Elements from a List
In Python, the simplest way to remove duplicate elements from a list is by using the set()
function. This method converts the list into a set (which contains only unique elements) and then converts it back to a list. Note that this approach does not preserve the original order.
Method 1: Using set() (Order Not Preserved)
# Original list
my_list = [1, 2, 2, 3, 4, 4, 5, 1]
# Remove duplicates using set
unique_set = set(my_list)
# Convert back to list
unique_list = list(unique_set)
print(unique_list) # Output: [1, 2, 3, 4, 5] (order may vary)
Method 2: Using a for Loop (Order Preserved)
# Original list
names = ['Lim', 'Kim', 'Park', 'Choi', 'Jung', 'Lee', 'Lim', 'Park']
# Create a new list to store unique elements
my_list_unique_ordered = []
# Iterate through the list and add elements only if they are not already in the new list
for name in names:
if name not in my_list_unique_ordered:
my_list_unique_ordered.append(name)
print(my_list_unique_ordered)
# Output: ['Lim', 'Kim', 'Park', 'Choi', 'Jung', 'Lee']
Key Points
- set(): Quick and simple, but original order is not preserved.
- for loop: Preserves the order while removing duplicates, slightly slower for large lists.
SEO Keywords
Python remove duplicates, Python list unique elements, Python set() example, Python for loop remove duplicates, remove repeated items Python
These methods allow you to remove duplicate elements from a Python list efficiently, depending on whether you need to preserve the order or not.
Good0 Bad0
댓글목록
등록된 댓글이 없습니다.