How can duplicates be removed in Python?
Python can utilize the set() function for deduplication. The set() function converts an iterable object into a set, where the elements are unique and duplicates are eliminated.
Here is a sample code demonstrating how to use the set() function for removing duplicates:
# 定义一个包含重复元素的列表
nums = [1, 2, 3, 4, 3, 2, 1]
# 使用set()函数进行去重
unique_nums = set(nums)
# 将集合转换为列表
result = list(unique_nums)
print(result)
The output is [1, 2, 3, 4], showing that duplicate elements have been removed.