user298519
user298519

Reputation: 1190

Python: Making a recursive function that takes a list, and returns a list containing elements of the previous list but no duplicates?

Here is the non-recursive code I came up with.

def newlst(lst):
    new_lst = []

    for element in lst:
        if element not in new_lst:
            new_lst.append(element)

    return new_lst

Now here is my attempt at a recursive version:

def newlst(lst):
    new_lst = []

    if lst == []:
        return new_lst

    if lst[0] in new_lst:
        new_lst.append(lst[0])
    else:
        return newlst(lst[1:])

I'm aware that I assign newlst to an empty list value each time the function calls itself and I don't know where else to assign it... So I'm lost.

Upvotes: 0

Views: 71

Answers (2)

rawrtillyoudrop
rawrtillyoudrop

Reputation: 11

def newlst(lst):  
    if lst == []:
        new_list = []          
    elif lst[0] in lst[1:]:
        new_list = newlst(lst[1:])        
    else:
        new_list =[lst[0]]+ newlst(lst[1:])                        
    return new_list

Upvotes: 0

AChampion
AChampion

Reputation: 30268

Agree this is an awful way of removing duplicates, but if you really want a recursive solution:

def newlst(lst):
    if not lst:
        return lst

    new_lst = newlst(lst[1:])
    return new_lst if lst[0] in new_lst else [lst[0]] + new_lst

>>> newlst([1,1,2])
[1, 2]

Upvotes: 1

Related Questions