2

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.

I got this solution from other post:

def unique_elements(a):
    newlist = []
    for i in a:
        if i not in newlist:
                newlist.append(i)
    return newlist

Also, I am not yet exposed to SETs in Python. So could someone let me know if my original code can work?

Karthik S
  • 11,348
  • 2
  • 11
  • 25
  • *Also, I am not yet exposed to SETs in Python. So could someone let me know if my original code can work?* The linked question has sets – Sash Sinha Feb 08 '19 at 04:44
  • `set` are not ordered so in your case they will not serve the purpose. Find my answer below. – Sociopath Feb 08 '19 at 04:48

1 Answers1

1

Try this

def unique_elements(a):
    newlist = []
    for i in a:
        if i not in newlist:
            newlist.append(i)
    return newlist


xyz = [1,1,2,4,6,2,2,4,5]

print(unique_elements(xyz))

Output:

[1, 2, 4, 6, 5]
Sociopath
  • 13,068
  • 19
  • 47
  • 75