Understanding Sets in Python: A Beginner's Guide
In Python, sets are an unordered collection of unique elements, meaning no duplicates. They're incredibly useful when we need to deal with large amounts of data and care only about the unique elements.
Key Characteristics of Sets:
Unordered: Elements in a set don’t follow a specific sequence.
Mutable: We can add or remove items from a set.
Unique Elements: Duplicate items are automatically removed.
No Indexing: Unlike lists or tuples, sets do not support indexing, slicing, or other sequence-like behavior.
Creating a Set:
We can create a set using curly braces {}
or the set()
function.
my_set = {1, 2, 3, 4}
Operations on Sets:
Python provides several built-in methods to interact with sets:
Adding Elements: We use the
add()
method to insert a new element.Removing Elements: We can remove an element using
remove()
ordiscard()
. The difference is thatremove()
will raise an error if the element doesn’t exist, whilediscard()
won’t.
Set Operations: Sets are perfect for operations like union, intersection, and difference:
Union (
|
orunion()
): Combines elements from two sets without duplicates.Intersection (
&
orintersection()
): Only includes elements found in both sets.Difference (
-
ordifference()
): Elements present in one set but not the other.
Subset and Superset: We can check if one set is a subset or superset of another using issubset()
and issuperset()
.Removing
Applications of Sets:
Duplicates: One of the most common uses of sets is to remove duplicates from a list or other iterable.
Our continued Example:
def days_to_units(num_of_days, conv_unit):
if conv_unit == "hours":
return f"{num_of_days} days are {num_of_days * 24} hours"
elif conv_unit == "min":
return f"{num_of_days} min are {num_of_days * 24 * 60} min"
else:
return "unsupported"
def validate_exe():
try:
user_inp_num = int(days_and_units_dictionary["days"])
if user_inp_num > 0 :
calc_value = days_to_units(user_inp_num, days_and_units_dictionary["unit"])
print(calc_value)
elif user_inp_num == 0:
print("you entered 0")
else:
print("negative num")
except ValueError:
print("not a valid num")
user_inp = " "
while user_inp != "exit":
user_inp = input("input no of days and conversion unit\n")
days_and_units = user_inp.split(":")
# print(days_and_units)
days_and_units_dictionary = {"days": days_and_units[0], "unit": days_and_units[1]}
# print(days_and_units_dictionary)
validate_exe()
Conclusion:
Sets in Python are like a handy tool for managing collections when we only care about unique items. They make it very easy to remove duplicates, perform quick checks, and do common operations like combining or comparing groups of data. Once we get the hang of using sets, they become a go-to solution for a lot of everyday coding tasks, making our code not only faster but also cleaner and easier to understand.