Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Python để loại bỏ các phần tử trùng lặp khỏi một danh sách?

Một danh sách được đưa ra với phần tử trùng lặp, nhiệm vụ của chúng tôi là tạo một danh sách khác chứa phần tử không trùng lặp.

Ví dụ

A::[2,3,4,3,4,6,78,90]
Output::[2,3,4,6,78,90]

Thuật toán

Step 1: create a list.
Step 2: create a new list which is empty.
Step 3: traverse every element in list.
Step 4: if element is not present in the list return true.
Step 5: append in the new list.
Step 6: display new list.

Mã mẫu

#  To remove duplicate elements
defremoveduplicateele(A):
   newlist = []
   for n in A:
      if n not in newlist:
         newlist.append(n)
   returnnewlist
# Driver Code
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the number ::")
fori in range(int(n)):
   k=int(input(""))
   A.append(int(k))
print("THE NEW LIST IS ::>",removeduplicateele(A))

đầu ra

Enter the size of the List ::5
Enter the number ::
10
20
30
20
10
THE LIST IS ::> [10, 20, 30]