´╗┐Scalable-Python-programming languages-Python-courses-python-exercises

Exercise 21

Write a Python algorithm that returns the list of duplicate elements of a given list. Example if L = [7, 23, 5, 12, 7, 19, 23, 12, 29], the algorithm returns the list: [7, 23, 12]

Solution

def listDuplicate (L):
# initialize the list of duplicate elements
duplicate = []
for x in L:
if L.count (x)> 1 and x not in duplicate:
duplicate.append (x)
return duplicate
#Example
L = [7, 23, 5, 12, 7, 19, 23, 12, 29]

print ("the list of duplicate elements of L is:", listDuplicate (L))
# The output is: the list of duplicate elements of L is: [7, 23, 12]

Younes Derfoufi
my-courses.net

Leave a Reply