Add in list with recursion | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Add in list with recursion

I want to create a function with parameter an int element and a list of int. I would like to return a list with the element added, but with each element unique. For that I should do it with recursion and without using set, add, in, ... I have something like this: if len(theList) == 0 : return [element] else: return [element] + addR(theList[0], theList[1:]) It works but I don't know how to remove not unique elements...

27th Mar 2020, 9:39 AM
Mickaël TREZZY
Mickaël TREZZY - avatar
5 Answers
+ 2
if theList.count(element) == 0: #do what u want here
27th Mar 2020, 9:58 AM
Mo Hani
Mo Hani - avatar
+ 1
You could make a seperate list and run a for loop over the original lost and only append in items that are not already in the list if you do not want to use a set.
27th Mar 2020, 9:52 AM
Ram
+ 1
Mo Hani thank you so much it works like this!
27th Mar 2020, 10:01 AM
Mickaël TREZZY
Mickaël TREZZY - avatar
0
The problem is I cannot use in, so I cannot do a for loop, and it seems I cannot use a while neither... I don't understand this exercise :(
27th Mar 2020, 9:56 AM
Mickaël TREZZY
Mickaël TREZZY - avatar
0
What do you mean of recursion?
1st Apr 2020, 5:35 AM
Elizabeth Busadre