0

This seems a bit odd! I did a program which required me removing duplicated from the list and choose the second last number. I did it using set(). however I came up with something unexpected.

set([32.0,36.0,39.0,40.0])

gives me an output of [32.0, 40.0, 36.0, 39.0]. I want to know why this happens. I'm using python 3.9.1 Thanks in advance

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • 1
    This isn't odd. This happens because set objects have no order, the order you get from iterating over a set is not guaranteed (it's arbitrary but consistent within a process). This is generally a property of hash-based containers, although python dict objects *do* maintain insertion order despite being hash-based – juanpa.arrivillaga Feb 08 '21 at 17:43
  • Is there any function of removing duplicates while keeping the order? – Andrious Prime Feb 09 '21 at 06:12

2 Answers2

1

Try below one

from collections import OrderedDict
list(OrderedDict.fromkeys([10,2,2,1,10,3,3]))
Guimoute
  • 4,407
  • 3
  • 12
  • 28
Ram
  • 72
  • 2
0

As you are using Python 3.7 or later you can use a dictionary instead of a set.

>>> l = [32.0,36.0,39.0,40.0]
>>> l[:] = list(dict.fromkeys(l))
>>> l
[32.0, 36.0, 39.0, 40.0]

The keys will be ordered by the order of insertion into the dictionary.

mhawke
  • 84,695
  • 9
  • 117
  • 138