Create a set of unique numbers from a list
This Python code uses a set comprehension to create a set named unique_numbers that contains the unique elements from the list numbers. Here's how the code works:
- numbers = [1, 2, 3, 2, 4, 5, 1]: This line initializes a list named numbers containing several integers, including some repeated values.
- unique_numbers = {x for x in numbers}: This line initializes the set unique_numbers using a set comprehension.
- for x in numbers: This part of the code sets up a loop that iterates through each element in the numbers list.
- {x}: For each element, this part includes it in the unique_numbers set. However, because sets do not allow duplicate elements, only the unique elements are included in the resulting set.
- print(numbers): This line of code prints the original numbers list to the console.
- print(unique_numbers): This line of code prints the unique_numbers set to the console.
Source Code
numbers = [1, 2, 3, 2, 4, 5, 1]
unique_numbers = {x for x in numbers}
print(numbers)
print(unique_numbers)
Output
[1, 2, 3, 2, 4, 5, 1]
{1, 2, 3, 4, 5}