Python: Is order preserved when iterating a tuple?

Python: Is order preserved when iterating a tuple?

Problem Description:

In Python, if I run the code:

for item in T:

Can I be sure that D will be organized as:

D = {0:'A', 1:'B', 2:'C', 3:'D'}

I know that tuples’ order cannot be changed because they are immutable, but am I guaranteed that it will always be iterated in order as well?

Solution – 1

Yes, tuples are ordered and iteration follows that order. Guaranteed™.

You can generate your D in one expression with enumerate() to produce the indices:

D = dict(enumerate(T))

That’s because enumerate() produces (index, value) tuples, and dict() accepts a sequence of (key, value) tuples to produce the dictionary:

>>> T = ('A', 'B', 'C', 'D')
>>> dict(enumerate(T))
{0: 'A', 1: 'B', 2: 'C', 3: 'D'}

Solution – 2

Since tuples are sequences (due to The standard type hierarchy) and are ordered by implementation, it has the __iter__() method to comply with the Iterator protocol which means that each next value of the tuple just yielded in the same ordered fashion because point the same object.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.