jeudi 7 février 2019

List returning unique values from another list in Python

I need to create a new list that contains unique values from another list, also order has to be maintained. My code:

def unique_elements(a):
    newlist = []
    for i in range(len(a)):
        if a[i] not in a[i+1:] and a[i-1::-1] :
                newlist.append(a[i])
    return newlist

Output is:

unique_elements([1,2,2,3,4,3])
[1, 2, 4, 3]

I am getting semi correct result, in that order is not maintained. Correct output should be:

[1,2,3,4]

Could someone please let me know where I am going wrong.

Aucun commentaire:

Enregistrer un commentaire