Is there a canonical way to check whether an iterable is ordered?
Tim Chase
python.list at tim.thechases.com
Thu Sep 18 10:32:15 EDT 2014
On 2014-09-18 08:58, 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.
>
> list1 = [item for item in i]
> list2 = [item for item in i]
>
> am I guaranteed that list1 == list2? It will be for all the
> collections I can think of in the standard library,
For stdlib *collections*, yes, but if you're just talking generic
iterators, then it can become exhausted in the first:
with open('example.txt') as f:
list1 = [item for item in f]
list2 = [item for item in f]
assert list1 == list2, "Not equal"
The OP would have to track the meta-information regarding whether the
iterable was sorted.
At least for dicts, order is guaranteed by the specs as long as the
container isn't modified between iterations[1], but I don't see any
similar claim for sets.
You can always test the thing:
def foo(iterable):
if isinstance(iterable, (set, frozenset)):
iterable = sorted(iterable)
for thing in iterable:
do_stuff(thing)
but nothing prevents that from being called with an unsorted list.
That said, sorting in the stdlib is pretty speedy on pre-sorted lists,
so I'd just start by sorting whatever it is that you have, unless
you're positive it's already sorted.
-tkc
[1]
https://docs.python.org/2/library/stdtypes.html#dict.items
More information about the Python-list
mailing list