DEV Community

Bonface Thuo
Bonface Thuo

Posted on

🎟️ DAY 6: Sets

Welcome back to Day 6! πŸš€ We’ve looked at lists, tuples, and dictionaries. By now, you’re practically a data hoarder. But what happens when you have a list of user sign-ups, and because of a system glitch, "JohnDoe123" accidentally signed up four different times?

If you leave those duplicates in your database, your analytics are going to be completely ruined. You need a data structure that acts like a strict VIP nightclub bouncer no duplicates allowed, and no specific order guaranteed.

Enter Sets! πŸŽŸοΈπŸ›‘

🎟️ What is a Set?

A Set is an unordered collection of unique items. This means two things:

No Duplicates: If you try to add the same thing twice, the set quietly deletes the duplicate.

No Order: Items float around randomly inside. Because there is no order, sets do not have indices! You cannot use [0] to get the first item.

To create a set, you use curly braces {} (just like dictionaries, but without the colons and keys!):

# A list of server logs with annoying duplicates πŸ“‘
raw_usernames = {"mario", "luigi", "mario", "bowser", "luigi"}

print(raw_usernames)
# Prints: {'mario', 'luigi', 'bowser'} (Magic! The duplicates vanished!)
Enter fullscreen mode Exit fullscreen mode

πŸ› οΈ Modifying a Set

Because sets don't use indices, we use dedicated built-in methods to add or drop items from our collection:

game_lobby = {"player_one", "player_two"}

# 1. Adding an item βž•
game_lobby.add("player_three")

# 2. Trying to add a duplicate (Python will just ignore this)
game_lobby.add("player_one") 

# 3. Removing an item ❌
game_lobby.remove("player_two")

print(game_lobby)
Enter fullscreen mode Exit fullscreen mode

πŸš€ Today's Challenge πŸ†

Create a set named backpack_items containing a few duplicates (e.g., {"apple", "potion", "apple", "shield"}).

Print the set to confirm the duplicate item was automatically vaporized.

Use .add() to add a "map" to your set.

Try printing backpack_items[0] and watch Python throw a spectacular TypeError. (Remember: No indices allowed in the set club!). Comment it out so your code runs clean.

Show me your duplicate-free sets in the comments! Tomorrow, we learn how to write secret notes in our code using Comments! πŸ“

Top comments (0)