Remember
set() constructs a mutable collection of unique hashable elements. Do not rely on set iteration order.
set() constructs a mutable collection of unique hashable elements. Do not rely on set iteration order.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
items = [3, 2, 2]
print(sorted(set(items)))Top-level scope
[3, 2, 2]set() constructs a mutable collection of unique hashable elements. Do not rely on set iteration order.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
items = [3, 2, 2]
print(sorted(set(items)))
|
v
DISPLAYED RESULT
[2, 3]
FINAL BINDINGS
items --> object 1 (list)
object 1: [3, 2, 2]Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
items = [3, 2, 2]
print(sorted(set(items)))Top-level scope
[3, 2, 2]The example has finished. Compare the final output with the values and references above.
[2, 3]
What do you expect this program to print?
items = [3, 2, 2]
print(sorted(set(items)))set() FunctionThe set() function in Python is used to create a set object. A set is an unordered collection of unique items — meaning it automatically removes duplicates.
set([iterable])
iterable – (Optional) Any iterable such as list, tuple, string, or dictionary keys.set object containing unique elements.numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers)
{1, 2, 3, 4, 5}
text = "banana"
letters = set(text)
print(letters)
{'b', 'a', 'n'}
Note: The order may vary because sets are unordered.
empty = set()
print(empty)
set()
Warning: Using {} creates an empty dict, not a set.
data = ["apple", "banana", "apple", "cherry"]
unique_fruits = list(set(data))
print(unique_fruits)
['banana', 'cherry', 'apple']
(Order may vary)
{} is an empty dictionary, not a set — use set() for an empty setset() is often used in coding problems involving uniqueness, duplicates, or fast lookups without ordering.
set() converts iterables into a set of unique elementsset(), not {}, to create an empty setWrite a program to read 5 names from the user and display only the unique names entered.
names = []
for _ in range(5):
names.append(input("Enter a name: "))
print("Unique names:", set(names))
Connect what you noticed in the example with the idea below.
set() constructs a mutable collection of unique hashable elements. Do not rely on set iteration order.
set() retains duplicate elements.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.