1

I am having a list which contains some elements with repetition and from this list I want to generate a list which has no repeated elements in it AND also maintains theie Order in the List.

I tried set(['1','1','2','3','4','4','5','2','2','3','3','6']) and got the output as set(['1', '3', '2', '5', '4', '6'])

But I want the output as set(['1', '2', '3', '4', '5', '6']) i.e. maintain the relative order of the elements already present.

How to do this??? Thanks in advance...

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Mayank Jain
  • 1,057
  • 2
  • 9
  • 6

1 Answers1

1

One way to do this:

In [9]: x = ['1','1','2','3','4','4','5','2','2','3','3','6']

In [10]: s = set()

In [11]: y = []

In [12]: for i in x:
    ...:     if i not in s:
    ...:         y.append(i)
    ...:         s.add(i)
    ...:         

In [13]: y
Out[13]: ['1', '2', '3', '4', '5', '6']

As noted by Martijn, a set is unordered by definition, so you need a list to store the result. See also this old question.

Community
  • 1
  • 1
Bas Swinckels
  • 18,095
  • 3
  • 45
  • 62