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

Steven D'Aprano steve+comp.lang.python at
Fri Sep 19 13:58:50 CEST 2014

Chris Angelico wrote:

> On Fri, Sep 19, 2014 at 8:59 PM, Steven D'Aprano
> <steve+comp.lang.python at> wrote:
>>> """If keys, values and items views are iterated over with no
>>> intervening modifications to the dictionary, the order of items will
>>> directly correspond."""
>>> 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(),
>> Not so! So long as the iteration of values() matched the *second*
>> iteration of keys(), it would be allowed. There's nothing which says that
>> the first iteration of keys() has to match the second.
> I disagree. Between the first iteration of keys() and the iteration of
> values(), there were no modifications to the dictionary - another
> iteration over keys() isn't a modification - ergo the guarantee ought
> to hold.

All it says is that keys/values/items will correspond, not keys/keys, etc.

Hmmm. On second thought, there is a problem with this:

a = list(mydict)
c = list(mydict.items())  # now the internal order is shuffled
b = list(mydict.values())
assert list(zip(a, b)) == c

and the assertion fails.

So I guess that rules out dict internal order changing during a single run
of the interpreter, unless the dict is modified.

Anyway, that's just dicts. Custom iterables can change any time they like.


More information about the Python-list mailing list