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

后端 未结 3 1372
误落风尘
误落风尘 2021-01-01 10:53

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

3条回答
  •  无人及你
    2021-01-01 11:04

    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.

提交回复
热议问题