I have an example where the iteration order of a python generator expression seems to be different from the analogous list comprehension and generator function.
For example, the code
n = 10
d = {i : str(i) for i in range(n)}
for i in d:
print d[i],
print
def func_gen(d):
for i in range(n):
yield d[i]
print(list(func_gen(d)))
g = [d[i] for i in range(n)]
print(g)
g = {d[i] for i in range(n)}
print(list(g))
has the output
0 1 2 3 4 5 6 7 8 9
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
['1', '0', '3', '2', '5', '4', '7', '6', '9', '8']
I would expect the generator expression to produce an ordered output like it does with the list comprehension. Is there something about generator expressions that says the order isn't guaranteed?
Why is the order for the generator expression different from the others, even though the constructs are almost identical? It isn't even the same order as iterating through the dictionary, so it doesn't seem like it's deferring to that.
I'm seeing the same behavior in Python 2 and 3.
Dicts aren't ordered. You can't rely on their items to come back in any particular order, even between function calls.