Search code examples
pythonset

Python: order in a set of numbers


With this code:

print set(a**b for a in range(2, 5) for b in range(2, 5))

I get this answer:

set([64, 256, 4, 8, 9, 16, 81, 27])

Why it isn't sorted?


Solution

  • Sets are not ordered collections in python or any other language for that matter.

    Sets are usually implemented using hash keys (hash codes). So order is probably related to how hash functions are used instead of natural order of its elements.

    If you need order, please do consider using a list.