Unlock the Power of Sets in Python
When working with data in Python, understanding sets is crucial. A set is an unordered collection of unique elements, and the set()
function is the key to creating them.
The Anatomy of set()
The set()
function takes a single optional parameter: iterable
. This can be a sequence (like a string or tuple), a collection (like a set, dictionary, or list), or even an iterator object. The iterable
parameter is used to construct the set.
What Does set() Return?
The set()
function returns one of two things:
- An empty set if no parameters are passed
- A set constructed from the given
iterable
parameter
Creating Sets from Various Data Types
Let’s explore some examples of creating sets from different data types.
Strings, Tuples, Lists, and Ranges
Here’s an example of creating sets from these data types:
“`
Create sets from string, tuple, list, and range
stringset = set(“hello”)
tupleset = set((1, 2, 3))
listset = set([4, 5, 6])
rangeset = set(range(7, 10))
“
set()
**Note:** Be careful not to confuse empty sets with empty dictionaries. To create an empty set, use, not
{ }`.
Sets, Dictionaries, and Frozen Sets
We can also create sets from other sets, dictionaries, and frozen sets:
“`
Create sets from another set, dictionary, and frozen set
setset = set({1, 2, 3})
dictset = set({“a”: 1, “b”: 2}.items())
frozen_set = set(frozenset({4, 5, 6}))
“`
Custom Iterable Objects
But what if we have a custom iterable object? No problem! We can create a set from that too:
“`
Create set() for a custom iterable object
class CustomIterable:
def init(self):
self.data = [7, 8, 9]
def __iter__(self):
return iter(self.data)
customiterable = CustomIterable()
customset = set(custom_iterable)
“
set()` function, you’ll unlock the full potential of working with sets in Python.
By mastering the