python
Python program to convert a List to Set
To convert a Python List to Python Set, you can use the methods and code examples explained in this post.
# define a list
my_list = ['a', 'b', 'c', 'd', 'e']
# use set function to convert
result_set = set(my_list)
# print the result
print(result_set)
Output
{'c', 'b', 'e', 'd', 'a'}
We are using the set() function in the above code example to convert a Python List to a Set.
Use set() function to make Set from List
This is the easiest method to convert a List to Python Set. We will be using the set() function of Python to convert it. The basic syntax is as below.
Syntax
set(List)
The set() function takes List as a parameter and converts it to Set.
Code Example
# define a list
my_list = [10, 20, 30, 40, 50, 60, 70]
# use set function to convert
result_set = set(my_list)
# print the result
print(result_set)
Output
{70, 40, 10, 50, 20, 60, 30}
Using List Comprehension
We can also use List Comprehension to convert a List to a Python Set. We are explaining it by using the below code example.
Code Example
# define a list
my_list = [10, 20, 30, 40, 50, 60, 70]
# use list comprehension to convert to set
result_set = {item for item in my_list}
# print the result
print(result_set)
Output
{70, 40, 10, 50, 20, 60, 30}
Use Python For loop to convert List to Set
If you do not want to use any function or modules to convert a List to Python Set then you can use Python For loop. Beloe is a code example.
# define a list
my_list = [10, 20, 30, 40, 50, 60, 70]
# use for loop to convert List to Set
result = set()
for item in my_list:
result.add(item)
# print the result
print(result)
# define a list
my_list = [10, 20, 30, 40, 50, 60, 70]
# use {} for List to Set conversion
result = {*my_list}
# print the result
print(result)
# -> {70, 40, 10, 50, 20, 60, 30}
You can also use {} - Curley Brackets to convert a List to a Set. In the above code example, we have defined a list - my_list that contains multiple elements. We are converting it to a List using {}.
Was this helpful?
Similar Posts
- # Python Program - Pattern Program 2
- # Python Program - Convert Hexadecimal to Binary
- Convert a List of Strings to List of Integers in Python
- Python3 program to iterate over a list
- [Python] Using comprehension expression to convert list of dictionaries to nested dictionary
- Convert pandas DataFrame to List of dictionaries python
- Convert JSON string to Python collections - like list, dictionaries