Extract Elements from list in set - Python
Last Updated :
23 Jul, 2025
We are given a list and our task is to extract unique elements from list in a set. For example: a = [1, 2, 3, 4, 5, 2, 3, 6] here we would only extract those elements from list which are unique hence resultant output would be {1,2,3,4,5,6}.
Using Set Conversion
In this method we convert the list into a set which automatically removes duplicate elements. As a result, the set contains only unique elements, and its length gives the count of distinct items.
Python
a = [1, 2, 3, 4, 5, 2, 3, 6]
# Convert the list to a set to remove duplicates and store unique elements
u = set(a)
print(f"Unique elements: {u}")
OutputUnique elements: {1, 2, 3, 4, 5, 6}
Explanation:
- List "a" is converted to a set using set(a) which removes any duplicate elements keeping only unique values.
- Resulting set "u" contains unique elements from original list and they are printed.
Using Loop and Set
Using a loop and a set we can iterate through list and add each element to set ensuring that only unique elements are stored set automatically handles duplicates and its size will give count of distinct elements.
Python
a = [1, 2, 3, 4, 5, 2, 3, 6]
u = set()
# Iterate through each element in the list
for element in a:
# Add the element to the set
u.add(element)
print(f"Unique elements: {u}")
OutputUnique elements: {1, 2, 3, 4, 5, 6}
Explanation:
- We initialize an empty set and iterate through the list adding each element to set which automatically eliminates any duplicates.
- Finally it prints unique elements in set which contains only distinct values from original list.
Using filter() with set
Using filter() with a set allows filtering elements from a list by applying a condition and set automatically ensures only unique elements are included in the result. The filtered elements are then stored in a set to remove duplicates.
Python
a = [1, 2, 3, 4, 5, 2, 3, 6]
# Use filter() to select elements greater than 3
u = set(filter(lambda x: x > 3, a))
print(f"Unique elements greater than 3: {u}")
OutputUnique elements greater than 3: {4, 5, 6}
Explanation:
- filter() function is used with a lambda to select elements from list a that are greater than 3 and result is passed to set() to ensure uniqueness.
- output is unique elements greater than 3 from original list.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice