Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have an ordered set?

Tags:

python

set

Python has an ordered dictionary. What about an ordered set?

like image 756
Casebash Avatar asked Oct 31 '09 10:10

Casebash


People also ask

Does Python have ordered set?

Python is a versatile programming language with a few options for creating ordered sets. You can use the OrderedSet class to get the job done, or you can do so manually if needed.

Is set ordered in Python 3?

Due to changes in dict implementation in Python 3.6 it is now ordered by default.

Why set is ordered Python?

A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.

Is Python list ordered?

Python Lists. The important characteristics of Python lists are as follows: Lists are ordered. Lists can contain any arbitrary objects.


2 Answers

There is an ordered set (possible new link) recipe for this which is referred to from the Python 2 Documentation. This runs on Py2.6 or later and 3.0 or later without any modifications. The interface is almost exactly the same as a normal set, except that initialisation should be done with a list.

OrderedSet([1, 2, 3]) 

This is a MutableSet, so the signature for .union doesn't match that of set, but since it includes __or__ something similar can easily be added:

@staticmethod def union(*sets):     union = OrderedSet()     union.union(*sets)     return union  def union(self, *sets):     for set in sets:         self |= set 
like image 88
Casebash Avatar answered Oct 19 '22 22:10

Casebash


The answer is no, but you can use collections.OrderedDict from the Python standard library with just keys (and values as None) for the same purpose.

Update: As of Python 3.7 (and CPython 3.6), standard dict is guaranteed to preserve order and is more performant than OrderedDict. (For backward compatibility and especially readability, however, you may wish to continue using OrderedDict.)

Here's an example of how to use dict as an ordered set to filter out duplicate items while preserving order, thereby emulating an ordered set. Use the dict class method fromkeys() to create a dict, then simply ask for the keys() back.

>>> keywords = ['foo', 'bar', 'bar', 'foo', 'baz', 'foo']  >>> list(dict.fromkeys(keywords)) ['foo', 'bar', 'baz'] 
like image 22
jrc Avatar answered Oct 19 '22 22:10

jrc