Contents
Convert List to Set
Sometimes, because of the differences in how elements are stored in a list, or set, we may need to convert a given List of elements into a Set in Python.
In this tutorial, we shall learn how to convert a list into set. There are many ways to do that. And we shall discuss the following methods with examples for each.
- Use set() builtin function.
- Unpack List inside curly braces.
Method 1: Use set() builtin function
set() builtin function can take any iterable as argument, and return a set object formed using the elements from the given iterable.
In the following program, we take a list of strings, and convert it into a set.
Python Program
#take a list of elements
list1 = ['apple', 'banana', 'cherry']
#convert list into set
output = set(list1)
print(f'Set : {output}')
print(type(output))
Run Output
Set : {'apple', 'banana', 'cherry'}
<class 'set'>
If there are any duplicates in the given list object, they are ignored. A set can contain only unique elements.
In the following program, we take a list of strings where some of the elements are repeated inside the list (duplicates), and convert it into a set.
Python Program
#take a list of elements
list1 = ['apple', 'banana', 'cherry', 'banana', 'cherry']
#convert list into set
output = set(list1)
print(f'Set : {output}')
print(type(output))
Run Output
Set : {'cherry', 'apple', 'banana'}
<class 'set'>
Method 2: Unpack List inside Curly Braces
We can also unpack the items of List inside curly braces to create a set.
In the following program, we have a list of strings, and we shall unpack the elements of this list inside curly braces.
Python Program
#take a list of elements
list1 = ['apple', 'banana', 'cherry']
#unpack list items and form set
output = {*list1}
print(f'Set : {output}')
print(type(output))
Run Output
Set : {'cherry', 'banana', 'apple'}
<class 'set'>
Summary
In this tutorial of Python Examples, we learned how to convert a Python List into a Set in different ways, with the help of well detailed example programs.
Related Tutorials
- Python – Count the items with a specific value in the List
- Python – Check if Element is in List
- Python List of Lists
- Python Program to Find Unique Items of a List
- How to Get the list of all Python keywords?
- Python List – Add Item
- How to Check if Python List is Empty?
- How to Insert Item at Specific Index in Python List?
- Python List of Dictionaries
- Python Program to Find Smallest Number in List