|
| Home |
|---|
In Python programming, lists and sets are both used to store collections of values. However, sets have one important feature: they automatically remove duplicate values.
When a list is converted into a set, Python removes duplicate elements and keeps only unique values.
numbers = [1,2,3,2,4,3,5]
print(numbers)
[1, 2, 3, 2, 4, 3, 5]
The most common way to convert a list into a set is by using
the built-in set() function.
numbers = [1,2,3,2,4,3,5]
unique_numbers = set(numbers)
print(unique_numbers)
{1, 2, 3, 4, 5}
The duplicate values are automatically removed.
Lists containing text values can also be converted into sets.
fruits = ["apple","banana","apple","mango"]
unique_fruits = set(fruits)
print(unique_fruits)
{'apple', 'banana', 'mango'}
A common use of converting lists to sets is removing duplicate values.
numbers = [10,20,20,30,30,40]
unique = set(numbers)
print(unique)
{40, 10, 20, 30}
Sometimes we remove duplicates using a set and then convert the result back into a list.
numbers = [1,2,2,3,3,4]
unique_list = list(set(numbers))
print(unique_list)
[1, 2, 3, 4]
Converting a list to a set in Python is useful when duplicate values need to be removed.
The set() function is the easiest way to convert
a list into a set containing only unique elements.
Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.
Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net