4. Identify the error in the following code snippet:
my_set = set{1, 2, 3}
print(my_set)
medium
A. SyntaxError due to incorrect set creation syntax
B. Prints {1, 2, 3} correctly
C. TypeError because set() expects a list
D. NameError because set is not defined
Solution
Step 1: Check set creation syntax
The correct way to create a set using the function is set() with parentheses, not curly braces.
Step 2: Identify syntax error
set{1, 2, 3} is invalid syntax and causes a SyntaxError.
Final Answer:
SyntaxError due to incorrect set creation syntax -> Option A
Quick Check:
Use set() with parentheses, not braces [OK]
Hint: Use parentheses with set(), not curly braces [OK]
Common Mistakes:
Using curly braces after set instead of parentheses
Confusing set() with dictionary syntax
Assuming set is undefined
5. Given the list nums = [1, 2, 2, 3, 4, 4, 5], which code snippet correctly creates a set of unique elements from this list?
hard
A. unique_nums = {nums}
B. unique_nums = set(nums)
C. unique_nums = list(set(nums))
D. unique_nums = {1, 2, 3, 4, 5}
Solution
Step 1: Understand how to convert list to set
The set() function can take an iterable like a list and return a set of unique elements.
Step 2: Analyze each option
unique_nums = {nums} creates a set with the entire list as one element (invalid). unique_nums = set(nums) correctly converts the list to a set. unique_nums = list(set(nums)) converts to set then back to list, which is not a set. unique_nums = {1, 2, 3, 4, 5} manually writes the set but is not dynamic.
Final Answer:
unique_nums = set(nums) -> Option B
Quick Check:
Use set() on list to get unique elements [OK]
Hint: Use set() on list to get unique items fast [OK]
Common Mistakes:
Trying to put list inside curly braces directly
Converting set back to list when set is needed
Hardcoding values instead of using the list variable