I'm confused by the behavior of Python's set()
in this example:
random_number_list = [randint(1, 10) for _ in range(10)]
# This will be sorted!
unique_numbers = set(random_number_list)
print(
f"random_number_list/unique_numbers with same upper bound for randint() and range():\n{random_number_list=}\n{unique_numbers=}\n"
)
random_number_list = [randint(1, 100) for _ in range(10)]
# This will not be sorted.
unique_numbers = set(random_number_list)
print(
f"random_number_list/unique_numbers with different upper bound for randint() and range():\n{random_number_list=}\n{unique_numbers=}\n"
)
It seems like set()
is sorting the random_number_list
if the length of the list and the upper bound of randint()
are the same:
➜ ch-2 python --version
Python 3.10.0
➜ ch-2 python find_k_smallest.py
random_number_list/unique_numbers with same upper bound for randint() and range():
random_number_list=[10, 1, 2, 5, 5, 7, 8, 8, 2, 8]
unique_numbers={1, 2, 5, 7, 8, 10}
random_number_list/unique_numbers with different upper bound for randint() and range():
random_number_list=[35, 1, 17, 26, 17, 74, 26, 11, 44, 13]
unique_numbers={1, 35, 74, 11, 44, 13, 17, 26}
The docs state:
A set object is an unordered collection of distinct hashable objects.
What's going on here? Why is set()
sorting the random_number_list
in certain cases and not others?
Edit Neither of these questions addresses my issue: