Python – Convert List to Set

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.

1. Convert List to Set using 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 Code Copy

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 Code Copy

Output

Set : {'cherry', 'apple', 'banana'}
<class 'set'>

2. Convert List to Set by 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 Code Copy

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

Code copied to clipboard successfully 👍