I'm just starting out learning python set comprehensions. Why does { 2**x for x in {0,1,2,3,4} } return {8, 1, 2, 4, 16} instead of the ordered {1, 2, 4, 8, 16}?
Asked
Active
Viewed 257 times
0
Martijn Pieters
- 963,270
- 265
- 3,804
- 3,187
paradox
- 1,228
- 5
- 20
- 32
-
3Python sets are not ordered; there's no "instead of", since those are the same set. – Wooble Jul 17 '13 at 12:06
-
And of [python set changes element order?](http://stackoverflow.com/q/9792664) and [Set Comprehension in python](http://stackoverflow.com/a/17446318) – Martijn Pieters Jul 17 '13 at 12:20
-
Note http://code.activestate.com/recipes/576694/ – Jakob Bowyer Jul 17 '13 at 12:22
-
I think this has been updated in python 3 to be ordered more often – Brendan Metcalfe Jun 07 '20 at 18:31
1 Answers
3
Mathematically speaking, sets do not have an order. When displaying or iterating over a set, Python obviously needs to provide a particular order, but this order is arbitrary and not to be relied on. The order is, however, fixed for a particular set; iterating over the same, unmodified set will produce the same order each time.
chepner
- 446,329
- 63
- 468
- 610