深度阅读

how to remove duplicates from a list in Python?

作者
作者
2023年08月22日
更新时间
12.07 分钟
阅读时间
0
阅读量

To remove duplicates from a list in Python, there are several methods you can use.

  1. Using the set() function: The set() function returns a collection of unique elements. You can convert the list to a set, and then convert the set back to a list to remove duplicates. For example:
my_list = [1, 2, 3, 3, 4, 4, 5]
my_list = list(set(my_list))
print(my_list)  # [1, 2, 3, 4, 5]
  1. Using a loop: You can loop through the list and append all unique elements to a new list. For example:
my_list = [1, 2, 3, 3, 4, 4, 5]
new_list = []
for i in my_list:
   if i not in new_list:
       new_list.append(i)
print(new_list)  # [1, 2, 3, 4, 5]
  1. Using a list comprehension: You can use a list comprehension to define a new list with unique elements. For example:
my_list = [1, 2, 3, 3, 4, 4, 5]
new_list = [i for n, i in enumerate(my_list) if i not in my_list[:n]]
print(new_list)  # [1, 2, 3, 4, 5]

Note that these methods preserve the order of the original list. If you don’t need to preserve the order, you can use the set() function directly to remove duplicates, as shown in the first example above.

I hope this helps you to remove duplicates from a list in Python.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。