Exercise 29
Write a Python program that removes duplicate items from a list.
Solution
First method
# -*- coding: utf-8 -*-
# define a function that remove duplicate element in list
def removeDuplicate(l):
# define and initialize list with no duplicate element
unique = []
# building a list with no duplicate element
for x in l:
if x not in unique:
unique.append(x)
return unique
# Example
l = [2, 7, 13, 2, 17, 13, 2, 7, 13]
print(removeDuplicate(l))
Second method
# -*- coding: utf-8 -*-
# define a function that remove duplicate element in list
def removeDuplicate(l):
# convert the list l to a set
SET = set(l)
# reconvert the set SET to a list
L = list(SET)
return L
# Example
l = [2, 7,7, 13, 2, 17, 17, 13, 15, 15, 2, 7, 13]
print(removeDuplicate(l))
Younes Derfoufi