Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 749
MrPat Avatar asked Sep 04 '14 16:09

MrPat


1 Answers

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'}
like image 108
Martijn Pieters Avatar answered Oct 17 '22 13:10

Martijn Pieters