Is there a canonical way to check whether an iterable is ordered?

Chris Angelico rosuav at gmail.com
Fri Sep 19 07:40:06 CEST 2014


On Fri, Sep 19, 2014 at 3:15 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> However, as far as I am aware, there are no built-ins that will fail that
> test, yet. Although the iteration order of dicts and sets is arbitrary, I
> think that (at least to date) it will be the same order every time you
> iterate over the dict or set within a single run of the Python interpreter.
> (Provided the dict or set hasn't changed.)
>
> That's not a language guarantee though. It's an implementation detail. In
> principle, it could be different each time:
>
> s = set("abcd")
> list(s)
> => returns ['d', 'a', 'b', 'c']
> list(s)
> => returns ['c', 'a', 'd', 'b']

Possibly for the set, but the dict is guaranteed some measure of stability:

https://docs.python.org/3.4/library/stdtypes.html#dict-views
"""If keys, values and items views are iterated over with no
intervening modifications to the dictionary, the order of items will
directly correspond."""

Also, a little above:
"""
iter(d)

Return an iterator over the keys of the dictionary. This is a shortcut
for iter(d.keys()).
"""

So if iterating over d.keys() and then d.values() with no mutations is
guaranteed to give the same order, then so is iterating over d.keys(),
then d.keys(), then d.values(), and since there's no magic in
iterating over d.values(), it logically follows that iterating over
d.keys() twice will give the same order.

But yes, it's conceivable that the set might change iteration order
arbitrarily. I don't know of any good reason for it to, but it
certainly isn't forbidden.

ChrisA



More information about the Python-list mailing list