0

In Python, is it possible to copy a set in the same order as the original? For example, rather than:

>>> s = {'r','g','b'}
>>> t = {i for i in s}
>>> t
set(['r', 'b', 'g'])
>>> 

Can t be set to:

{'r','g','b'}
13
  • Why don't you use a list then? Commented Mar 16, 2014 at 16:56
  • 2
    No. Sets aren't ordered. If you want order you need another data structure - a list or and OrderedSet. Commented Mar 16, 2014 at 16:56
  • 3
    @gjdanis Sets have no order, so you can’t copy the original order simply because there wasn’t an order to begin with. Commented Mar 16, 2014 at 17:04
  • 1
    @gjdanis But sets simply don’t have an order. Commented Mar 16, 2014 at 17:14
  • 3
    @gjdanis Several. Most and foremost, it’s way more efficient. If you have an order, then that order is part of the item’s property, making it harder to identify items with the same value (but different positions). Sets are implemented using hash tables, so they have a O(1) access; lists cannot work that and have a O(N) access instead. If there was a data structure that would support everything (efficient access, uniqueness, order) then that would be incredible cool, but it’s simply not possible; so you have to decide what you need and what you can pass on. Commented Mar 16, 2014 at 17:19

1 Answer 1

1

Try manipulating the OrderedDict from collections, see http://docs.python.org/2/library/collections.html#collections.OrderedDict.

>>> from collections import OrderedDict
>>> x = ['a','b','c','b','c']
>>> list(OrderedDict.fromkeys(x))
['a', 'b', 'c']
Sign up to request clarification or add additional context in comments.

Comments