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