-2
>>> nums = {n**2 for n in range(10)}
>>> nums
{0, 1, 64, 4, 36, 9, 16, 49, 81, 25}

I dont get why the numbers are out of order? Should it not be {0, 1, 4, 9...}?

Alonzo Robbe
  • 465
  • 1
  • 8
  • 23

2 Answers2

5

This is because you have created a set, and sets are unordered. If you wanted order, you should use a standard list comprehension:

>>> nums = [n**2 for n in range(10)]
>>> nums
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • What determines what order it is? Another computer gave the same output so surely its not a random order. – Alonzo Robbe Nov 19 '18 at 10:15
  • @AlonzoRobbe its the same as `num = []; for n in range(10): num.append(n**2)` just as list comp. See [Understanding list comps](https://stackoverflow.com/questions/38408991/understanding-list-comprehensions-in-python) - they are appended in order of creation - and lists are stable. – Patrick Artner Nov 19 '18 at 10:18
  • @AlonzoRobbe Items are stored in sets by their hash (which in the main CPython implementation is the number itself for small ints) but sets are dynamically resized as you add to them and Python does not reorder a set when it is resized. You should never count on any specific ordering in a set. – Daniel Roseman Nov 19 '18 at 10:25
4

You're just using a set. A set is an unordered data structure.

One approach could be using sorted method.

sorted_lst = sorted(nums)

Output

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128