Is there a canonical way to check whether an iterable is ordered?
Terry Reedy
tjreedy at udel.edu
Thu Sep 18 09:46:29 EDT 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
> set.
One can check whether the iterable is a tuple, list, range, or tuple or
list iterator (the latter not being re-iterable).
>>> type(iter([]))
<class 'list_iterator'>
>>> type(iter(()))
<class 'tuple_iterator'>
> 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?
Clearly not.
> 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
> astonishment?
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
mailing list