0

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?

kame
  • 20,848
  • 33
  • 104
  • 159
  • See [Python OrderedSet with .index() method](http://stackoverflow.com/questions/7998692/python-orderedset-with-index-method/7998819#7998819) for another `OrderedSet` question or http://code.activestate.com/recipes/576694/ for a good implementation; also [Does Python Have an Ordered Set?](http://stackoverflow.com/questions/1653970/does-python-have-an-ordered-set) – agf Nov 10 '11 at 18:59
  • what order were you expecting? `4, 8, 16, 9, 27, 81, 64, 256` or `4, 8, 9, 16, 27, 64, 81, 256` or something else? – John La Rooy Jul 01 '13 at 06:55

3 Answers3

10

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.

Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
3

Sets are by their nature unordered containers. From the documentation:

A set object is an unordered collection of distinct hashable objects.

They are implemented using a hash table, facilitating O(1) membership tests. If you need an ordered set, try OrderedDict.fromkeys():

from collections import OrderedDict
OrderedDict.fromkeys(a**b for a in range(2, 5) for b in range(2, 5))
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
0

sorted

Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable.

nums_set = set(a**b for a in range(2, 5) for b in range(2, 5))
# OR
# nums_set = {a**b for a in range(2, 5) for b in range(2, 5)}

print("sorted set =", sorted(nums_set))
# sorted set = [4, 8, 9, 16, 27, 64, 81, 256]

refs

https://docs.python.org/3/howto/sorting.html

xgqfrms
  • 10,077
  • 1
  • 69
  • 68