Jorge Arévalo
Jorge Arévalo

Reputation: 2998

does python 'for' clause iterate objects in the same order they were stored?

It may sound like a stupid question but if I have this

fruits = ['apple', 'banana', 'pear', 'orange']

for fruit in fruits:
  print fruit

Will I always get this result? (I mean, in this order)

apple
banana
pear 
orange

Upvotes: 1

Views: 67

Answers (1)

shaish
shaish

Reputation: 1499

Yes, it will be in the same order.

"The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence."

http://docs.python.org/2/tutorial/controlflow.html#for-statements

Upvotes: 1

Related Questions