duplicate values in python code example

Example 1: how to make python remove the duplicates in list

mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))

  print(mylist)

Example 2: python has duplicates

def has_duplicates(lst):
    return len(lst) != len(set(lst))
    
x = [1,2,3,4,5,5]
has_duplicates(x) 			# True

Example 3: duplicate in list python

a = [1,2,3,2,1,5,6,5,5,5]

import collections
print([item for item, count in collections.Counter(a).items() if count > 1])

## [1, 2, 5]

Example 4: program to print duplicates from a list of integers in python

lst = [ 3, 6, 9, 12, 3, 30, 15, 9, 45, 36, 12, 12]
dupItems = []
uniqItems = {}
for x in lst:
   if x not in uniqItems:
      uniqItems[x] = 1
   else:
      if uniqItems[x] == 1:
         dupItems.append(x)
      uniqItems[x] += 1
print(dupItems)

Example 5: find duplicates in list python

def Find_Repeated(x):
    x2=sorted(x)
    List_Of_Repeated=[]
    for i in x2:
        if x2.count(i)>1:
            List_Of_Repeated.append([i,x2.count(i)])
            for c in range(x2.count(i)):
                for j in x2:
                    if i==j and x2.count(i)>1:
                        x2.remove(i)
    List_Of_Repeated.sort()
    return List_Of_Repeated

List=[1,2,3,4,4,4,5,5,5,5,5,1,1,2,2,3,7,8,6]

# Repeated numbers: [1,2,3,4,5]

# Simple print output:

print(Find_Repeated(List),"\n")

# For a neat output:

print("[ Value , Times Repeated ] \n")
print("For example: [2,4]  The value 2 was repeated 4 times. \n")
for i in Find_Repeated(List):
    print(i)