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

By : Chris
Source: Stackoverflow.com
Question!

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

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

and:

``````itemlist = []
for item in myarray:
itemlist.append(item)
``````

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 ```
``` Related Questions Differences between python's numpy.ndarray and list datatypes Tuples Vs List Vs Numpy Arrays for Plotting a Boxplot in Python Calculating Correlation Coefficient with Numpy (adsbygoogle = window.adsbygoogle || []).push({}); Comparing rows elements in python Python/numpy append arrays, transpose, and save as csv Why does comparison of a numpy array with a list consume so much memory? Python: method to remove all duplicate points from a X,Y,Z file that have identical x and y coordinates Create numpy array with random elements from list List to array conversion How do I load both Strings and floats into a numpy array? Loading large arrays from file, numpy slower than list appending. Where is the bottle neck? Difference between a numpy array and a multidimensional list in Python? How to convert a tuple of depth 2 to a 2D Numpy array? Calculate mean of arrays in NumPy Zero outside the range of a list / array Converting a 1D numpy array to a list of lists numpy array to list formatting get the first few items order by item's count Python: Counting identical rows in an array (without any imports) ```
``` ```
``` About Us    Contact Us    Legal    feedback    Copyright © 2015 - All Rights Reserved - www.4answered.com ```