How to Convert List into Set in Python. In Python, converting a list to a set is a common operation, especially when you want to remove duplicates from a list or when you need to perform set operations like unions, intersections, and differences.
Table of Contents
Converting List into Set in Python
To convert a list to a set, we will use the set()
function. This function takes an iterable as an input and returns a new set containing the elements from the iterable, automatically removing any duplicates.
List to Set Conversion Python Code
# Example list with duplicates
example_list = [1, 2, 2, 3, 4, 4, 4, 5]
print("Original List:", example_list)
# Converting list to set
example_set = set(example_list)
print("Converted Set:", example_set)
In the above code –
- Start by creating a list in Python. Lists can contain duplicate elements and maintain the order of insertion
- Converted the list into a set, by using the
set()
function - After conversion, you can verify that the set contains only unique elements from the original list.
Why Convert a List to a Set?
- Removing Duplicates: The primary reason to convert a list to a set is to discard duplicate elements.
- Performance Improvement: Set operations like membership tests (
in
keyword) are faster in sets than in lists, especially for large collections.
Performing Set Operations in Python
# Example list with duplicates
example_list = [1, 2, 2, 3, 4, 4, 4, 5]
print("Original List:", example_list)
# Converting list to set
example_set = set(example_list)
print("Converted Set:", example_set)
# Another example list
another_list = [3, 4, 5, 6, 7]
another_set = set(another_list)
# Intersection of sets
intersection = example_set.intersection(another_set)
print("Intersection:", intersection)
# Union of sets
union = example_set.union(another_set)
print("Union:", union)
# Difference of sets
difference = example_set.difference(another_set)
print("Difference:", difference)
Things to Keep in Mind
- Order is Not Preserved: When converting a list to a set, the original order of elements is lost.
- Only Immutable Elements: Sets can only contain immutable (hashable) elements, so lists and dictionaries cannot be added to a set.
Converting a list to a set in Python is a straightforward process that provides numerous benefits, particularly when dealing with data that requires uniqueness or efficient performance for large datasets. By following this guide, you can easily convert lists to sets and utilize set operations to enhance your data manipulation capabilities in Python.
Happy Coding & Learning