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

alister alister.nospam.ware at ntlworld.com
Fri Sep 19 14:26:19 CEST 2014


On Fri, 19 Sep 2014 21:56:05 +1000, Chris Angelico wrote:

> On Fri, Sep 19, 2014 at 9:46 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> Chris Angelico wrote:
>>
>>> On Fri, Sep 19, 2014 at 8:59 PM, Steven D'Aprano
>>> <steve+comp.lang.python at pearwood.info> wrote:
>>>> Here's a proof of concept of what would be allowed:
>> [...]
>>> Also, this can't possibly offer the same guarantee. Watch:
>>>
>>> d = MyDict(some_lot_of_items)
>>> d.values(); d.items()
>>> # mutate the dict in whatever way you like pairs = zip(d.keys(),
>>> d.values())
>>>
>>> This might well create mismatched pairs, because after generating the
>>> keys() return value, the list gets shuffled, prior to generating
>>> values() in the same expression. This would not be allowed.
>>
>> That would be a bug, and an easy one to fix. Every mutation of the dict
>> would have to reset the internal flags back to the starting state.
> 
> What if there's no mutation, then? Just calling values() and items()
> means that the zip of keys and values will make mismatches.
> 
> ChrisA

As far as I understand it the order of keys in a dict is not guaranteed
iterating over the same dict twice (without changes) does not have to 
return the keys in the same order.

In my installation of python the order does remain constant unless the 
dict is modified but I am reasonably sure this is just due to 
implementation detail & should not be relied upon.

As simple amateur I may be mistaken.



-- 
"Tell the truth and run."
-- Yugoslav proverb



More information about the Python-list mailing list