1

I have sequence of integer elements in array "a" ,given below

a=[2,1,5,4,8,4,2,1,2,4,8,6,1,5,4,87,62,3]  

I need the output like

output=[2,1,5,4,8,6,87,62,3] 

I tried the built-in functions like set or unique but it arrange the
resulting sequence in ascending order, I want to keep the order unchanged.

Can anyone help?

faiz
  • 115
  • 1
  • 10

2 Answers2

3

You can use sorted with key=list.index

>>> a=[2,1,5,4,8,4,2,1,2,4,8,6,1,5,4,87,62,3]
>>> new_a = sorted(set(a), key=a.index)
>>> new_a
[2, 1, 5, 4, 8, 6, 87, 62, 3]
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
0
a=[2,1,5,4,8,4,2,1,2,4,8,6,1,5,4,87,62,3]  
b = []

You can use

[b.append(x) for x in a if x not in b]

or easier to read

for x in a:
    if x not in b:
        b.append(x)


>>> [2, 1, 5, 4, 8, 6, 87, 62, 3]`
tushortz
  • 3,697
  • 2
  • 18
  • 31