Home โบ Output practice โบ what a set really deduplicates
Predict the output: what a set really deduplicates
๐ฎ Predict the outputTopic: setsDifficulty: mediumNo login needed
The snippet
Two misconceptions meet here: that a set keeps the order you typed, and that items are only equal when they are the same type. 1, 1.0 and True are three different objects with one value โ so one of them survives.
flags = [1, True, 1.0, 0, False]
print(set(flags))
print(len(set(flags)))
Your prediction
Type exactly what this program prints โ one line per print() call:
The output
{0, 1}
2
Verified against CPython 3.11 in this repo's build
Line-by-line explanation
flags = [1, True, 1.0, 0, False]
Five elements, but only two distinct values once you compare by equality: 1 and 0.print(set(flags))
Sets store members byhashthen==.hash(1) == hash(True) == hash(1.0)and all three are equal, so the first one wins and the rest are ignored;0/Falsecollapse the same way. The surviving members are the ints โ{0, 1}.print(len(set(flags)))
Two members โ2.(why that order?)
Small integers hash to themselves, so in this build they land in slots 0 and 1 and print as{0, 1}. Never rely on it โ set order is an implementation detail, not insertion order. Usesorted()when order matters.
The rule you can reuse
A set keeps one representative per equal-and-same-hash value, in unspecified order. That is also why unhashable items (list, dict, set) cannot be members โ TypeError: unhashable type.
Why most predictions break here
Answering {1, True, 1.0, 0, False} or {1, 0} in insertion order. The count and the set of *values* are what a set promises; position is not.
Quick fire
Same rule, two more shapes. Predict first, then open.
Predict this too
print(sorted({3, 1, 2}))
print(len({1, 1.0, True}))Output[1, 2, 3]
1
sorted() turns a set into an ordered list, and the three "different" booleans/numbers are one member โ [1, 2, 3] then 1.
Predict this too
print(len([[1, 2], [1, 2]]), len({"a", "b"}))Output2 2
Lists are unhashable so {[1, 2]} raises TypeError; here nothing is deduplicated by the set literal at all โ 2 2.
Share your result
Challenge a friend โ the link contains the question, never the answer:
Copied โKeep practising this rule
More output questions โ All interactive problemsQuestions this page answers
Is dict key order the same thing?
No โ dictionaries *do* keep insertion order (a language guarantee since Python 3.7). Only sets are unordered.
Why does True not appear in the output at all?
Because 1 == True and both hash alike, the set keeps the member it saw first, which was 1. The same rule removes 1.0.