MrPat
MrPat

Reputation: 119

Python: Is order preserved when iterating a tuple?

In Python, if I run the code:

T=('A','B','C','D')
D={}
i=0
for item in T:
    D[i]=item
    i=i+1

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?

Upvotes: 6

Views: 4138

Answers (2)

storenth
storenth

Reputation: 1225

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.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121744

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'}

Upvotes: 22

Related Questions