0

Given a list as follows, deduplicating the list without concern for order, we can do this:

from collections import OrderedDict

x = [1,2,3,9,8,3,2,5,3,2,7,3,6,7]

list(set(x)) # Outputs: [1, 2, 3, 5, 6, 7, 8, 9]

If we want to keep the order, we can do something like:

list(OrderedDict.fromkeys(x)) # Outputs: [1, 2, 3, 9, 8, 5, 7, 6]

Using OrderedDict.fromkeys, then casting it into a list again is kept of cumbersome. And seem counter-intuitive but I suppose there's some reason for Python dev to decide on processing sets with ordering as dictionary instead.

Is there such an object as OrderedSet that can achieve the same deduplication while keeping order?

If there isn't, what is the motivation to support OrderedDict but not OrderedSet? Is it an anti-pattern to create a custom object like OrderedSet?

alvas
  • 115,346
  • 109
  • 446
  • 738
  • 5
    From Python 3.6+ you do not need to use OrderedDict since dict now keeps insertion order. `list({}.fromkeys(x))` – dawg Apr 07 '23 at 14:02
  • The dupe doesn't make sense @dawg. It's correct to observe that dictionary insertion order is preserved but it's not clear why it wasn't extended to sets – roganjosh Apr 07 '23 at 14:13
  • @roganjosh: If it is not a dup, it is kinda opinion. I reopened to let others decide. – dawg Apr 07 '23 at 14:16
  • I agree with the opinion side but I think it's explained in https://youtu.be/p33CVV29OG8 . I don't have chance right now to watch it to refamiliarise myself with it. I think he explains it somewhere in there, and there'll be a PEP somewhere – roganjosh Apr 07 '23 at 14:19

0 Answers0