Convert tuple to set
What You'll Learn: In this tutorial, you'll discover how to convert a tuple of elements into a set in Python. Sets are useful because they only store unique items and are not ordered.
Method 1: Using the set() Built-in Function
The set() function can take any iterable, like a tuple, and return a set object with the elements from that iterable.
Example Code:
# Take a tuple of elements
myTuple = ('apple', 'banana', 'cherry')
# Convert tuple into set
output = set(myTuple)
print(f'Set: {output}')
Output: Set: {'cherry', 'banana', 'apple'}
What's Happening Here?
set(myTuple)converts the tuplemyTupleinto a setoutput.
If the tuple has duplicate items, the set will only contain unique elements.
Example Code:
# Take a tuple of elements with duplicates
myTuple = ('apple', 'banana', 'cherry', 'banana')
# Convert tuple into set
output = set(myTuple)
print(f'Set: {output}')
Output: Set: {'cherry', 'banana', 'apple'}
Method 2: Unpacking Tuple Inside Curly Braces
You can also convert a tuple to a set by unpacking the tuple inside curly braces {}.
Example Code:
# Take a tuple of elements
myTuple = ('apple', 'banana', 'cherry', 'banana')
# Unpack tuple items and form set
output = {*myTuple}
print(f'Set: {output}')
Output: Set: {'cherry', 'banana', 'apple'}
What's Happening Here?
output = {*myTuple}unpacks the elements ofmyTupleinside curly braces, creating a setoutput.
Try It Yourself: Fun Exercises
- Convert Your Favorite Colors:
- Create a tuple of your favorite colors, including some duplicates.
- Convert this tuple to a set using the
set()function.
- Transform Your Snack List:
- Make a tuple of snacks you like.
- Convert this tuple to a set by unpacking the tuple inside curly braces.
Summary:
In this Python tutorial, we learned how to convert a tuple to a set using two methods: the set() function and unpacking the tuple 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 tuples and sets in Python!