0

Why does this set comprehension...

>>> {2**x for x in {0,1,2,3,4,5}}

Produce this answer?

{32, 1, 2, 4, 8, 16}

BUT!

This loop...

>>> for x in {0,1,2,3,4,5}:
...     print 2**x

Produces this answer.

1
2
4
8
16
32
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Pescolly
  • 922
  • 11
  • 18
  • `{0,1,2,3,4,5}` happens to be iterated over in ascending order. However, the resulting `set` isn't ordered any more. If you did a list comprehension instead of a set comprehension, you'd see the difference. – Tim Pietzcker Jul 01 '13 at 06:51
  • 1
    Try `for x in {5,4,3,2,1,0}` too. It's not safe to rely on the order or sets. If you loop over the same set twice without adding/removing elements, you will get the same order, but that's about it. – John La Rooy Jul 01 '13 at 06:59

0 Answers0