Is 'for x in array' always result in sorted x? [Python/NumPy]

By : Chris

For arrays and lists in Python and Numpy are the following lines equivalent:

itemlist = []
for j in range(len(myarray)):
    item = myarray[j]


itemlist = []
for item in myarray:

I'm interested in the order of itemlist. In a few examples that I have tried they are identical, but is it guaranteed? For example, I know that the foreach statement in C# doesn't guarantee order, and that I should be careful with it.

By : Chris


Yes, the Python Language Reference guarantees this (emphasis is mine):

 for_stmt ::=  "for" target_list "in" expression_list ":" suite
               ["else" ":" suite]

"The suite is then executed once for each item provided by the iterator, in the order of ascending indices."

By : earl

It is guaranteed for lists. I think the more relevant Python parallel to your C# example would be to iterate over the keys in a dictionary, which is NOT guaranteed to be in any order.

# Always prints 0-9 in order
a_list = [0,1,2,3,4,5,6,7,8,9]
for x in a_list:
    print x

# May or may not print 0-9 in order. Implementation dependent.
a_dict = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
for x in a_dict:
    print x

The for

By : Triptych

This video can help you solving your question :)
By: admin