Member-only story
PythonDay 8 of #100DaysOfCode in Python: Unraveling the World of Sets
Welcome to Day 8 of the #100DaysOfCode in Python! You’ve already embarked on a significant journey, uncovering various Python constructs, from basic variables and data types to lists and dictionaries. Today, we venture into another essential data structure — sets.
Introduction to Sets
A set is a collection of distinct elements, similar to mathematical sets. It’s akin to a dictionary with keys but no values or a list with no duplicate elements. It’s inherently unordered, meaning the elements don’t have a specific order.
Creating a Set
Creating a set is as simple as enclosing the elements within curly braces {}
or using the set()
constructor.
# Using curly braces
fruits = {"apple", "banana", "cherry"}
# Using set constructor
colors = set(["red", "green", "blue"])
Note: An empty set must be created using the set()
constructor as {}
will create an empty dictionary.
Unique Features of Sets
- Uniqueness: Sets automatically eliminate duplicate values.
- Unordered: The set elements don’t have an index and are unordered.