Contents
Convert Set to List
Sometimes, because of the differences in how elements are stored in a list, or set, we may need to convert a given Set of elements into a List in Python.
In this tutorial, we shall learn how to convert a given set into a list. There are many ways to do that. And we shall discuss the following methods with examples for each.
- Use list() builtin function.
- Use List Comprehension.
Method 1: Use list() builtin function
list() builtin function can take any iterable as argument, and return a list object formed using the elements from the given iterable.
In the following program, we take a set of strings, and convert it into a list.
Python Program
#take a set of elements
mySet = {'apple', 'banana', 'cherry'}
#convert set into list
output = list(mySet)
print(f'List : {output}')
Run Output
List : ['apple', 'cherry', 'banana']
Method 2: Use List Comprehension
In the following program ,we use List Comprehension and create a list from the elements of the Set.
Python Program
#take a set of elements
mySet = {'apple', 'banana', 'cherry'}
#create list from elements of set
output = [x for x in mySet]
print(f'List : {output}')
Run Output
List : ['banana', 'apple', 'cherry']
Summary
In this tutorial of Python Examples, we learned how to convert a Python Set into a List using different methods, with the help of well detailed example programs.
Related Tutorials
- Python – Convert List to Dictionary
- Python – List of Strings
- How to Reverse Python List?
- Python – Count the items with a specific value in the List
- How to Check if Python List is Empty?
- Python List with First N Elements
- How to Get the list of all Python keywords?
- How to Append List to Another List in Python? – list.extend(list)
- Python List – Add Item
- How to Sort Python List?