TiLapiot
TiLapiot

Reputation: 19

PYTHON3: Printing a set of random integers sometimes get sorted output, sometimes unsorted output! Why?

I'm a Python3 newcomer, and I recently get a strange behavior when printing a set of random integers. I sometimes get a perfectly sorted set, and sometimes not! Does somebody know the reason why?

Here is my Python3 code:

import random
n=random.randint(30,90)
print("n=",n)
ens=set()    
while len(ens)!=n:
    ens.add(random.randint(100,199))
print("len(ens)=",len(ens))
print("ens=",str(ens))
car=input("...?")

Here is one non-sorted resulting text:

n= 84

len(ens)= 84

ens= {128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 147, 148, 150, 151, 152, 154, 156, 157, 158, 160, 161, 162, 163, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 177, 178, 179, 181, 182, 183, 185, 186, 188, 189, 190, 192, 193, 194, 195, 196, 197, 198, 199, 100, 101, 102, 103, 104, 105, 106, 107, 108, 110, 111, 112, 113, 114, 116, 117, 118, 119, 121, 123, 124, 125, 126, 127}

...?

And another sorted resulting text:

n= 86

len(ens)= 86

ens= {100, 102, 103, 104, 105, 106, 107, 108, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 128, 129, 130, 131, 132, 133, 134, 136, 137, 138, 139, 140, 141, 142, 143, 144, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 168, 169, 170, 171, 173, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 186, 188, 189, 191, 192, 195, 196, 197, 198, 199}

...?

I know Python sets are unordered collection of items, but then, why do some of my outputs appear to be perfectly sorted, and some are not?

Just in case it is convincing, I either use Geany IDE, Thonny IDE, or directly Python 3.8 (under Win7 32bit).

Upvotes: 1

Views: 74

Answers (1)

chrisgallardo
chrisgallardo

Reputation: 28

Sets are unordered, so when you print your set, python doesn't know what order to print the items, so it prints them in sorted order.

>>> s = {5, 2, 3, 4, 6}
>>> print(s)
{2, 3, 4, 5, 6}

If you want to have the items ordered, use a list.

>>> l = [5, 2, 3, 4, 6]
>>> print(l)
[5, 2, 3, 4, 6]

Upvotes: 0

Related Questions