Python's Set Element Ordering Demystified
Sets in Python are unordered collections, but certain patterns emerge in their displayed order. Despite its seeming consistency, this order results from Python's hashing mechanism.
Hashing and Memory Placement
Python hashes each element and uses the last N bits of the hash as array indices for memory placement. The order of elements in memory thus determines their displayed order.
Collision Resolution
When two elements have the same hash, collision resolution mechanisms place them in alternative memory locations. The order of element insertion (if there is only one element or multiple elements with the same hash) influences the exact location of the elements in memory.
Example
In the following examples, the order of elements in the printed set is consistent because of collision resolution:
set_1 = set([5, 2, 7, 2, 1, 88]) set_1 # set([88, 1, 2, 5, 7]) set_2 = set([8, 16, 24]) set_2 # set([8, 16, 24])
Note that changing the insertion order in the input list may alter the displayed order if there are key collisions. For example:
set_3 = set([24, 16, 8]) set_3 # set([24, 16, 8])
Unique Hashes and Order Preservation
In cases where elements have unique hash values, the insertion order is preserved:
set_4 = set([1, 2, 3]) set_4 # set([1, 2, 3])
Note:
The described implementation applies to CPython's dict and set, and it may differ in certain versions. However, the general principle of hashing and memory placement remains the same.
The above is the detailed content of Why Does Python's Set Display Elements in a Seemingly Ordered Manner?. For more information, please follow other related articles on the PHP Chinese website!