Courses / Python
1. Sets
A set is an unordered collection of unique items.
How It Works
Think of a set like a box where you can only put in unique toys; if you try to add the same toy again, it just won't fit.
When you create a set, Python checks each item to ensure uniqueness.
See It
The code creates a set with initial items 1, 2, and 3. When trying to add 2 again, it does nothing since sets only allow unique items. The output will be `{1, 2, 3, 4}`. You could try adding a negative number to see how it behaves.
my_set = {1, 2, 3}
my_set.add(2) # Trying to add a duplicate
my_set.add(4) # Adding a new element
print(my_set)Use It
Removing duplicate entries from a list of user IDs.
user_ids = [101, 102, 103, 101, 104]
unique_user_ids = set(user_ids)
print(unique_user_ids)Using a set is efficient for filtering duplicates because it automatically handles uniqueness.
Break It
What will this print?
my_set = {1, 2, 3}
my_set.add(2) # Attempt to add a duplicate
print(len(my_set)) # Expecting 4The output is 3 because the set does not allow duplicates, so adding 2 again does not increase the size of the set.
To fix the misconception, you should check the contents of the set instead of just its length.
my_set = {1, 2, 3}
my_set.add(2)
print(my_set) # Should show {1, 2, 3}Level Up
Set Comprehensions: Set comprehensions allow creating sets in a concise way, which can enhance code readability and efficiency.
Set Operations: Understanding union, intersection, and differences between sets can optimize data manipulation and comparison tasks.
Prove It
Create a function that takes a list and returns a set of unique elements.
Python
Sets
A set is a collection of unique items that is unordered.
"I need to ensure my data has no duplicates without worrying about the order."
A set in Python is an unordered collection of distinct items, meaning it automatically removes duplicates and does not maintain any specific sequence.
"I need to ensure my data has no duplicates without worrying about the order."
A set in Python is an unordered collection of distinct items, meaning it automatically removes duplicates and does not maintain any specific sequence.