How to convert List to Set
In Python, converting a list to a set is a straightforward process. Let’s go step by step and understand the concepts and how the conversion works.
What is a List?
- A list is a collection of ordered and mutable (modifiable) items.
- Lists allow duplicate values.
Example:
my_list = [1, 2, 3, 4, 2, 3]
print(my_list)
Output:
[1, 2, 3, 4, 2, 3]
What is a Set?
- A set is an unordered and mutable collection of items.
- Sets do not allow duplicate values.
- Sets are used to store only unique items.
Example:
my_set = {1, 2, 3, 4}
print(my_set)
Output:
{1, 2, 3, 4}
Why convert a list to a set?
- To remove duplicates from the list.
- To perform set operations (union, intersection, difference, etc).
- To create a collection of unique items.
How to Convert a List to a Set
Python provides the set() function to convert a list into a set.
Syntax:
set(iterable)
iterable: Any iterable object (list, tuple, or string) can be passed toset().
Example 1: Basic Conversion
# Original list
my_list = [1, 2, 3, 4, 2, 3]
# Convert list to set
my_set = set(my_list)
print("List:", my_list)
print("Set:", my_set)
Output:
List: [1, 2, 3, 4, 2, 3]
Set: {1, 2, 3, 4}
Important Points to Remember
1. Order is not preserved in sets:
Sets do not maintain the order of elements.
my_list = [3, 1, 4, 1, 2]
my_set = set(my_list)
print(my_set)
Output:
{1, 2, 3, 4}
2. Duplicates are removed:
Any duplicate values in the list will be removed in the set.
my_list = [1, 2, 2, 3, 3, 3]
my_set = set(my_list)
print(my_set)
Output:
{1, 2, 3}
3. Set elements must be hashable:
Sets cannot contain mutable items like other lists or dictionaries.
my_list = [1, 2, [3, 4]]
my_set = set(my_list) # This will raise an error.
Error Output:
TypeError: unhashable type: 'list'
Use Cases of Converting a List to a Set
1. Removing duplicates:
my_list = [1, 2, 2, 3, 4, 4]
unique_list = list(set(my_list))
print(unique_list)
Output:
[1, 2, 3, 4]
2. Checking membership (faster in sets than lists):
my_set = {1, 2, 3, 4}
print(3 in my_set)
print(5 in my_set)
Output:
True
False
3. Performing set operations (union, intersection, difference):
set1 = set([1, 2, 3])
set2 = set([3, 4, 5])
print(set1 | set2) # Union
print(set1 & set2) # Intersection
print(set1 - set2) # Difference
Output:
{1, 2, 3, 4, 5}
{3}
{1, 2}
Full Example
# Original list
my_list = [1, 2, 3, 4, 2, 3, 5]
# Convert to set
my_set = set(my_list)
# Print results
print("Original List:", my_list)
print("Converted Set:", my_set)
Output:
Original List: [1, 2, 3, 4, 2, 3, 5]
Converted Set: {1, 2, 3, 4, 5}
Summary
- Lists are ordered and permit duplicates.
- Sets are unordered and eliminate duplicates.
- Converting a list to a set is useful for tasks requiring unique elements.
- Use the
set()function for this conversion.