Convert set to list

 

What You'll Learn: In this tutorial, you'll discover how to convert a set of elements into a list in Python. This can be useful because sets and lists have different properties.

Method 1: Using the list() Built-in Function

The list() function can take any iterable, like a set, and return a list object.

Example Code:

python
# Take a set of elements
mySet = {'apple', 'banana', 'cherry'}
# Convert set to list
output = list(mySet)
print(f'List: {output}')

Output: List: ['apple', 'banana', 'cherry']
 

What's Happening Here?

  • list(mySet) converts the set mySet into a list output.

Method 2: Unpacking Set Inside Square Brackets

You can also convert a set to a list by unpacking the set inside square brackets [].

Example Code:

python
# Take a set of elements
mySet = {'apple', 'banana', 'cherry'}
# Unpack set items and form list
output = [*mySet]
print(f'List: {output}')

Output: List: ['apple', 'cherry', 'banana']
 

What's Happening Here?

  • output = [*mySet] unpacks the elements of mySet inside square brackets, creating a list output.

Try It Yourself: Fun Exercises

  1. Convert Your Favorite Colors:
    • Create a set of your favorite colors.
    • Convert this set to a list using the list() function.
  2. Transform Your Snack List:
    • Make a set of snacks you like.
    • Convert this set to a list by unpacking the set inside square brackets.

Summary:

In this Python tutorial, we learned how to convert a set to a list using two methods: the list() function and unpacking the set inside square brackets. Lists are mutable, making them useful for scenarios where you need to change the items. Keep experimenting and have fun with sets and lists in Python!