Convert List to Set
What You'll Learn: In this tutorial, you'll discover how to convert a Python list to a set. Sets are like lists, but they only store unique items and don't keep them in order.
Method 1: Using the set() Built-in Function
The set() function can take any iterable, like a list, and return a set object with the elements from that iterable.
Example Code:
# Take a list of elements
list1 = ['apple', 'banana', 'cherry']
# Convert list into set
output = set(list1)
print(f'Set: {output}')
print(type(output))
Output:
Set: {'apple', 'banana', 'cherry'}
<class 'set'>What's Happening Here?
set(list1)converts the listlist1into a setoutput.
If the list has duplicate items, the set will only contain unique elements.
Example Code:
# Take a list of elements with duplicates
list1 = ['apple', 'banana', 'cherry', 'banana', 'cherry']
# Convert list into set
output = set(list1)
print(f'Set: {output}')
print(type(output))
Output:
Set: {'cherry', 'apple', 'banana'}
<class 'set'>Method 2: Unpacking List Inside Curly Braces
You can also convert a list to a set by unpacking the list inside curly braces {}.
Example Code:
# Take a list of elements
list1 = ['apple', 'banana', 'cherry']
# Unpack list items and form set
output = {*list1}
print(f'Set: {output}')
print(type(output))
Output:
Set: {'cherry', 'banana', 'apple'}
<class 'set'>What's Happening Here?
output = {*list1}unpacks the elements oflist1inside curly braces, creating a setoutput.
Try It Yourself: Fun Exercises
- Convert Your Favorite Fruits:
- Create a list of your favorite fruits, including some duplicates.
- Convert this list to a set using the
set()function.
- Transform Your Hobbies:
- Make a list of your hobbies.
- Convert this list to a set by unpacking the list inside curly braces.
Summary:
In this Python tutorial, we learned how to convert a list to a set using two methods: the set() function and unpacking the list inside curly braces. Sets are useful for storing unique items and can help you manage your data more efficiently. Keep experimenting and have fun with lists and sets in Python!