DEV Community

Programming Entry Level: for beginners sets

Understanding for Beginners Sets for Beginners

Have you ever needed to store a list of items, but you only wanted unique items? Maybe you're building a game and want to keep track of power-ups a player has collected, ensuring they don't get the same power-up twice. Or perhaps you're analyzing data and need to identify distinct categories. That's where "sets" come in! Understanding sets is a fundamental concept in programming, and it's something you'll encounter frequently, especially when preparing for technical interviews. This post will break down sets in a way that's easy to grasp, even if you're just starting out.

2. Understanding "for beginners sets"

Imagine you're making a guest list for a party. You wouldn't want to invite the same person twice, right? A set is like that guest list – it's a collection of unique items. Unlike a regular list (which we often call an "array" in programming), a set doesn't allow duplicates.

Think of it like this:

  • List (Array): [apple, banana, apple, orange] – Allows duplicates.
  • Set: {apple, banana, orange} – Only contains unique items. The duplicate "apple" is removed.

Sets are incredibly useful because they provide a quick and efficient way to:

  • Remove duplicates from a collection.
  • Check if an item exists in a collection.
  • Perform mathematical set operations like union, intersection, and difference (we won't dive deep into those here, but it's good to know they exist!).

Let's visualize this with a simple diagram:

graph LR
    A[List: [apple, banana, apple, orange]] --> B(Set: {apple, banana, orange});
    B --> C{Unique Items Only};
Enter fullscreen mode Exit fullscreen mode

This diagram shows how a list with duplicates can be converted into a set, automatically removing the repeated elements.

3. Basic Code Example

Let's see how sets work in Python. Python has a built-in set() function to create sets.

# Creating a set

my_set = {1, 2, 2, 3, 4, 4, 5}

# Printing the set

print(my_set)
Enter fullscreen mode Exit fullscreen mode

This code will output:

{1, 2, 3, 4, 5}
Enter fullscreen mode Exit fullscreen mode

Notice how the duplicate numbers (2 and 4) were automatically removed!

Now, let's look at adding and checking for elements:

# Adding an element to the set

my_set.add(6)
print(my_set)

# Checking if an element exists in the set

print(3 in my_set)  # Output: True

print(7 in my_set)  # Output: False

Enter fullscreen mode Exit fullscreen mode

Here's what's happening:

  1. my_set = {1, 2, 2, 3, 4, 4, 5}: This creates a set named my_set and initializes it with some numbers. Duplicates are automatically removed.
  2. print(my_set): This prints the contents of the set.
  3. my_set.add(6): This adds the number 6 to the set.
  4. print(3 in my_set): This checks if the number 3 is present in the set. The in operator is a very efficient way to check for membership in a set.
  5. print(7 in my_set): This checks if the number 7 is present in the set.

4. Common Mistakes or Misunderstandings

Let's look at some common pitfalls beginners encounter with sets.

❌ Incorrect code:

my_set = [] # Trying to create a set using a list

Enter fullscreen mode Exit fullscreen mode

✅ Corrected code:

my_set = {} # Creating an empty set

Enter fullscreen mode Exit fullscreen mode

Explanation: Using square brackets [] creates a list, not a set. Empty curly braces {} create an empty set. If you try to create a set with values using curly braces, it will work, but an empty set must use {}.

❌ Incorrect code:

my_set.add([1, 2]) # Trying to add a list to a set

Enter fullscreen mode Exit fullscreen mode

✅ Corrected code:

my_set.add((1, 2)) # Adding a tuple to a set

Enter fullscreen mode Exit fullscreen mode

Explanation: Sets can only contain immutable (unchangeable) elements. Lists are mutable, while tuples are immutable. That's why we use a tuple (1, 2) instead of a list [1, 2].

❌ Incorrect code:

my_set = {1, 2, 2, 3}
print(my_set[0]) # Trying to access an element by index

Enter fullscreen mode Exit fullscreen mode

✅ Corrected code:

my_set = {1, 2, 2, 3}
for item in my_set:
    print(item)
Enter fullscreen mode Exit fullscreen mode

Explanation: Sets are unordered. This means you can't access elements by index like you can with lists. You need to iterate through the set using a for loop to access its elements.

5. Real-World Use Case

Let's say you're building a simple program to find the unique words in a sentence.

def get_unique_words(sentence):
  """
  Finds the unique words in a sentence.
  """
  words = sentence.lower().split()  # Convert to lowercase and split into words

  unique_words = set(words)  # Create a set to remove duplicates

  return unique_words

sentence = "This is a sentence. This sentence is a test."
unique_words = get_unique_words(sentence)
print(unique_words)
Enter fullscreen mode Exit fullscreen mode

This code does the following:

  1. get_unique_words(sentence): This function takes a sentence as input.
  2. words = sentence.lower().split(): This converts the sentence to lowercase and splits it into a list of words.
  3. unique_words = set(words): This creates a set from the list of words, automatically removing duplicates.
  4. return unique_words: This returns the set of unique words.

The output will be:

{'this', 'is', 'a', 'sentence.', 'test'}
Enter fullscreen mode Exit fullscreen mode

6. Practice Ideas

Here are a few exercises to help you solidify your understanding of sets:

  1. Remove Duplicates: Write a function that takes a list as input and returns a new list containing only the unique elements from the original list.
  2. Common Elements: Write a function that takes two sets as input and returns a new set containing only the elements that are present in both sets (the intersection).
  3. Word Count: Write a program that reads a text file and counts the number of unique words in the file.
  4. Find the Difference: Given two sets of student IDs, find the students who are in the first set but not in the second set.
  5. Power-Up Tracker: Simulate a game where a player collects power-ups. Use a set to keep track of the power-ups the player has. Prevent the player from collecting the same power-up twice.

7. Summary

Congratulations! You've taken your first steps into the world of sets. You've learned what sets are, how to create them, how to add and check for elements, and how to avoid common mistakes. Sets are a powerful tool for managing unique data and can significantly simplify your code.

Don't be afraid to experiment with sets and try them out in different scenarios. Next, you might want to explore more advanced set operations like union, difference, and symmetric difference. Keep practicing, and you'll become a set pro in no time!

Top comments (0)