Is the order of results coming from a list comprehension guaranteed?

Dan picture Dan · Aug 17, 2009 · Viewed 8.9k times · Source

When using a list comprehension, is the order of the new list guaranteed in any way? As a contrived example, is the following behavior guaranteed by the definition of a list comprehension:

>> a = [x for x in [1,2,3]]
>> a
[1, 2, 3]

Equally, is the following equality guaranteed:

>> lroot = [1, 2, 3]
>> la = [x for x in lroot]
>> lb = []
>> for x in lroot:
     lb.append(x)
>> lb == la
True

Specifically, it's the ordering I'm interested in here.

Answer

Arkady picture Arkady · Aug 17, 2009

Yes, the list comprehension preserves the order of the original iterable (if there is one). If the original iterable is ordered (list, tuple, file, etc.), that's the order you'll get in the result. If your iterable is unordered (set, dict, etc.), there are no guarantees about the order of the items.