-2

I have a tuple of repeating numbers and would like to keep only the unique items but not change the order. This works:

values = (30.0,30.0,30.0,15.0,30.0]) print set(values)

which returns:

set([30.0, 15.0])

But when I try:

values = (2, 1, 2, 1)

It returns:

set([1, 2])

My question is why is it not keeping the order in the second example.

PhilL
  • 63
  • 5
  • 1
    Sets don't have order. – Simeon Visser Jul 17 '14 at 14:03
  • As said @SimeonVisser and don't have repeat elements. – Trimax Jul 17 '14 at 14:04
  • Duplicated question: http://stackoverflow.com/questions/9792664/python-set-changes-element-order?rq=1 – Yuan Jul 17 '14 at 14:05
  • 2
    This question appears to be off-topic because the OP should [RTFM](https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset). – jonrsharpe Jul 17 '14 at 14:05
  • 1
    It is a legitimate criticism to say that the OP should not pose a duplicate question, but attacking him for not reading the docs which he may not know about is not constructive and feels hostile. – eikonomega Jul 17 '14 at 14:11

1 Answers1

1

Sets have no concept of order, but you could use an OrderedDict to achieve what you want:

>>> from collections import OrderedDict
>>>
>>> values = (2, 1, 2, 1)
>>> list(OrderedDict.fromkeys(values))
[2, 1]
>>>
>>> values = (30.0, 30.0, 30.0, 15.0, 30.0)
>>> list(OrderedDict.fromkeys(values))
[30.0, 15.0]
arshajii
  • 127,459
  • 24
  • 238
  • 287