Python: Is order preserved when iterating a tuple?
Asked Answered
T

2

6

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?

Toole answered 4/9, 2014 at 16:52 Comment(2)
Yes, it is guaranteed that the tuple will be iterated over in that order. Dictionaries however are unordered, so you can't rely on their order (the key:value mapping will be guaranteed to be the way you showed it though). Use collections.OrderedDict if you need an order preserving dictionary.Courtroom
@LukasGraf Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.Julius
N
22

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'}
Noguchi answered 4/9, 2014 at 16:53 Comment(2)
And now I see that I can use enumerate(T,start) to begin my indices with some offset. I'm reading blocks of memory from an embedded device and I want to map it into a dictionary whose keys are the memory addresses from the embedded device. Perfect. Thanks.Toole
@gabroncancio: your link is nice, but doesn't actually document the iteration behaviour. I had not added the link myself for that reason.Noguchi
J
0

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.

Julius answered 26/11, 2022 at 9:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.