Mayank Jain
Mayank Jain

Reputation: 1077

maintain relative order in a set

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...

Upvotes: 1

Views: 303

Answers (1)

Bas Swinckels
Bas Swinckels

Reputation: 18488

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.

Upvotes: 1

Related Questions