How do I check duplicate elements present in an array?
In Python It is a simple program, Let see step by step.
Steps:
Firstly initialize a list1 with the duplicate elements.
initialize an empty list2.
Take a for loop for list1.
check if the list1 element is not in list2 then append the element of list1 into list2.
Let’s See an example of it:
- # Using naive method
- list1=[1,2,3,1,3,4,5,6,7,3,4,6,7]
- print("original list is: " +str(list1))
- list2=[]
- for i in list1:
- if i not in list2:
- list2.append(i)
- print ("list after removing duplicates element is : " + str(list2))
- # Using list comprehension method
- list1=[1,2,3,1,3,4,5,6,7,3,4,6,7]
- print("original list is: " +str(list1))
- list2=[]
- [list2.append(i) for i in list1 if i not in list2]
- print("list after removing duplicates element is: " + str(list2))
Comments
Post a Comment