[ACCEPTED]-Is 'for x in array' always result in sorted x? [Python/NumPy]-numpy
Yes, it's entirely guaranteed. for item in myarray
(where 5 myarray
is a sequence, which includes numpy's arrays, builtin 4 lists, Python's array.arrays, etc etc), is 3 in fact equivalent in Python to:
_aux = 0
while _aux < len(myarray):
item = myarray[_aux]
...etc...
for some 2 phantom variable _aux
;-). Btw, both of your 1 constructs are also equivalent to
itemlist = list(myarray)
It is guaranteed for lists. I think the 8 more relevant Python parallel to your C# example 7 would be to iterate over the keys in a dictionary, which 6 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 5 for <element> in <iterable>
structure only worries that the iterable
supplies 4 a next()
function which returns something. There 3 is no general guarantee that these elements 2 get returned in any order over the domain 1 of the for..in
statement; lists are a special case.
Yes, the Python Language Reference guarantees this (emphasis is mine):
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
"The 2 suite is then executed once for each item 1 provided by the iterator, in the order of ascending indices."
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.