Convert List to Set in Python (3 Examples)
Hello! This tutorial will show you 3 ways of converting a list into a set in Python.
First, though, here is an overview of this tutorial:
Let’s dive right into it!
Create Sample List
First, we will create a Python list for demonstration. In your Python IDE, run the code below:
my_list = [1,2,3,4,5,6]
As seen, my_list contains 6 integers.
Example 1: Form Sets from Lists Using set() Function
In this example, we will use the Python set()
function to convert the list into a set.
my_set = set(my_list) print(my_set) # {1, 2, 3, 4, 5, 6} print(type(my_set)) # <class 'set'>
You can check above how the type is now a set for the created object my_set. For details, see the type() function.
Example 2: Form Sets from Lists Using Set Comprehension
In this next example, we will use set comprehension to create a set from my_list.
my_set = {x for x in my_list} print(my_set) # {1, 2, 3, 4, 5, 6} print(type(my_set)) # <class 'set'>
As desired, the new object my_set is now a Python set.
Example 3: Form Sets from Lists Using for Loop
In this final example, we will use a for loop to switch the data type from lists to sets.
my_set = set() for i in my_list: my_set.add(i) print(my_set) # <class 'set'> print(type(my_set)) # {1, 2, 3, 4, 5, 6}
That’s it, I hope you found this tutorial helpful. Enjoy your sets!
Video, Further Resources & Summary
Do you need more explanations on how to convert a list into a set in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.
In the video, we explain how to convert a list into a set in Python.
The YouTube video will be added soon.
Furthermore, I encourage you to check out other interesting Python list tutorials on Statistics Globe, starting with these ones:
- Sort List of datetime Objects in Python (Example)
- Count Duplicates in List in Python(2 Examples)
- Access List Element by Index in Python (3 Examples)
- List in Python (Beginner & Advanced)
- Convert List from Character String to Integer in Python(2 Examples)
- Learn Python Programming
This post has shown how to convert a list into a set in Python. In case you have further questions, you may leave a comment below.
This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.
Statistics Globe Newsletter