Sets

Python Sets: The "Unique Collector"

Imagine you have a big bag of marbles, and you want to know which different colors you have. You don't care if you have ten blues; you just want to know that "Blue" is there. In Python, we use a set to keep a collection of items where every single one is one-of-a-kind.

What is a Set?

A set is a collection that is unordered, unindexed, and most importantly, only contains unique items.

  • No Duplicates: If you try to add the same number twice, the set will automatically delete the extra one.

  • Curly Braces: We create sets using { } brackets.

  • Unordered: Python doesn't remember what order you put things in. It's like a messy toy box—everything is in there, but not in a neat line.

  • No Index: Since there is no order, you cannot ask for "item number 0."

Real-World Set Scenarios

  • Student IDs: Making sure no two students have the same ID number.

  • Data Cleaning: Taking a long list of words and removing all the repeats.

  • Common Interests: Finding which hobbies two friends both share (Intersection).

  • Website Tags: Managing a list of unique tags for a blog post.

How it Looks (Syntax & Examples)

The Pattern:

set_name = {item1, item2, item3}


Example 1: Removing Duplicates Automatically

nums = {1, 2, 2, 3}
print(nums)


Output:
{1, 2, 3}

Example 2: Finding Common Items (Intersection)

a = {1, 2, 3}
b = {3, 4, 5}
print(a & b)


Output:
{3}

Summary:

  • Duplicate Destroyer: Use a set whenever you want to get rid of repeat values instantly.

  • Math Magic: Sets are great for "set math" like finding things that are in both groups (Intersection) or combining groups (Union).

  • Speed: Sets are incredibly fast for checking if an item is "in" the collection.

Check your knowledge

Quickly verify what you've learned from this tutorial.

Question 1

Which brackets are used to create a Set in Python?

Python sets are always defined using curly braces { }.

Question 2

What happens if you put ["apple", "apple", "apple"] into a set?

Sets automatically remove any duplicate values, keeping only unique items.

Question 3

Why can't you use print(my_set[0])?

Unlike lists, sets do not have a specific order, so items don't have an "index" or seat number.

Question 4

Which operation would you use to find items that are in BOTH Set A and Set B?

An Intersection (using the & symbol) finds only the common items shared between two sets.

Question 5

Which of the following is the best reason to use a Set instead of a List?

The main power of a set is its ability to handle unique data and perform fast filtering.

Congratulations!

You've successfully mastered the knowledge check for "Sets."

For more questions and practice, click the link below:

Practice More Questions
Previous Topic Tuples Next Topic Dictionaries