How to check for duplicate elements in Python?

You can use the following method to check if a list has duplicate elements:

  1. By using the set() function, you can convert a list into a set. Sets do not allow duplicate elements, so if the list contains duplicates, the length will decrease when converted to a set.
lst = [1, 2, 3, 4, 5, 6, 6]  
if len(lst) != len(set(lst)):
    print("列表中有重复元素")
else:
    print("列表中没有重复元素")
  1. By employing loops and counters: iterate through each element in a list using a loop, then use a counter to tally the number of times that element appears in the list; if the count is greater than 1, the list contains duplicate elements.
lst = [1, 2, 3, 4, 5, 6, 6]
duplicates = False
for i in range(len(lst)):
    count = 0
    for j in range(len(lst)):
        if lst[i] == lst[j]:
            count += 1
    if count > 1:
        duplicates = True
        break
if duplicates:
    print("列表中有重复元素")
else:
    print("列表中没有重复元素")

These methods can also be applied to other iterable objects, such as tuples, strings, and so on.

bannerAds