0

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}?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
paradox
  • 1,248
  • 5
  • 20
  • 32

1 Answers1

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
  • 497,756
  • 71
  • 530
  • 681