Python Program to remove duplicate elements from the list

Here, we will figure out how to expel copy components from the list in python? To expel copy components, we will affix the extraordinary components to another list.

Example:

    Input:
    list1:  [10, 20, 10, 20, 30, 40, 30, 50]

    Output:
    List after removing duplicate elements
    list2:  [10, 20, 30, 40, 50]

Rationale/Logic:

  • To actualize the program is excessively simple, we need to affix components individually to another list by checking whether the component is accessible in the new list or not.
  • Let assume, 20 is accessible multiple times in the list list1 and when we annex 20 (first event) to the list list2, it will be affixed, however when we add 20 (second event) to the list list2, the condition will be bogus and the thing won’t be attached. Lastly, we will get the list without copy components.

Program:

# declare list 
list1 = [10, 20, 10, 20, 30, 40, 30, 50]

# creating another list with unique elements
# declare another list 
list2 = []

# appending elements 
for n in list1:
	if n not in list2:
		list2.append(n)

# printing the lists 
print "Original list"
print "list1: ", list1
print "List after removing duplicate elements"
print "list2: ", list2

Output:

    Original list
    list1:  [10, 20, 10, 20, 30, 40, 30, 50]
    List after removing duplicate elements
    list2:  [10, 20, 30, 40, 50]

Program (Defining User characterizes work):

# Function to remove duplicates 
def removeDuplicates (list1):
	# declare another list
	list2 = []

	# appending elements 
	for n in list1:
		if n not in list2:
			list2.append (n)
	return list2

# Main code
# declare a list
list1 = [10, 20, 10, 20, 30, 40, 30, 50]
# print the list 
print "Original list: ", list1
print "List after duplicate remove: ", removeDuplicates (list1)

Output:

    Original list:  [10, 20, 10, 20, 30, 40, 30, 50]
    List after duplicate remove:  [10, 20, 30, 40, 50]

Leave a Comment