Is there a canonical way to check whether an iterable is ordered?
tjreedy at udel.edu
Thu Sep 18 15:46:29 CEST 2014
On 9/18/2014 8:58 AM, Roy Smith wrote:
> I suspect what he meant was "How can I tell if I'm iterating over an
> ordered collection?", i.e. iterating over a list vs. iterating over a
One can check whether the iterable is a tuple, list, range, or tuple or
list iterator (the latter not being re-iterable).
> Is there anything which requires an iterator to be deterministic?
No. An iterator can yields random number, input from a non-deterministic
source -- human or mechanical, or items from a collection in shuffled
order. Generator that do such can easily be turned into the __iter__
method of a class.
> For example, let's say I have an iterable, i, and I do:
> list1 = [item for item in i]
> list2 = [item for item in i]
If i is an iterator or other non-reiterable, list2 will be empty.
If i is an instance of a class with a non-deterministic __iter__ method,
list2 will not necessarily be either empty or a copy of list1.
> am I guaranteed that list1 == list2?
> It will be for all the collections I can think of in the standard
library, but if I wrote my own class with
> an __iter__() which yielded the items in a non-deterministic order,
> would I be violating something other than the principle of least
There should not be any astonishment. 'Iterable' is a much broader
category than 'deterministically re-iterable iterable'.
Terry Jan Reedy
More information about the Python-list