Sets - 35.2.1 | 35. Sets, stacks, queues | Data Structures and Algorithms in Python
K12 Students

Academics

AI-Powered learning for Grades 8–12, aligned with major Indian and international curricula.

Academics
Professionals

Professional Courses

Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.

Professional Courses
Games

Interactive Games

Fun, engaging games to boost memory, math fluency, typing speed, and English skillsβ€”perfect for learners of all ages.

games

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Introduction to Sets

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Today, we’re discussing sets in Python, which are collections of unique items. Can anyone tell me what sets differ from lists?

Student 1
Student 1

Sets don’t allow duplicates while lists do!

Teacher
Teacher

Exactly! For example, if I create a set from the list ['apple', 'banana', 'apple'], it will only include 'apple' and 'banana'. Remember, a key feature of a set is uniqueness.

Student 2
Student 2

How do we create an empty set in Python?

Teacher
Teacher

Great question! We use `set()` to create an empty set because `{}` is already reserved for dictionaries. Let’s remember this as the 'Set Specialty: `set()`!'

Membership Testing in Sets

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Now that we understand sets, let’s consider how to check if an item is in a set. Who knows the syntax for this?

Student 3
Student 3

Is it using the `in` keyword?

Teacher
Teacher

Exactly! For instance, `if 'banana' in my_set:` will check for 'banana'. It returns `True` if present, otherwise `False`. This makes it easy to ensure uniqueness!

Student 4
Student 4

What happens if we check for an item not in the set?

Teacher
Teacher

That will return `False`. Remember, these membership tests are efficient, which is why sets are great for checking existing unique items quickly.

Mathematical Operations in Sets

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Let’s move on to operations we can perform with sets. Who can name any set operations?

Student 1
Student 1

We can find a union, intersection, and difference!

Teacher
Teacher

Correct! The union combines elements from both sets. For example, `set1.union(set2)` will merge them into one, removing duplicates. It’s like a marriage of sets!

Student 2
Student 2

How about intersection?

Teacher
Teacher

Intersection finds what's common. If `set1` has `{'1', '2', '3'}` and `set2` has `{'2', '3', '4'}`, intersecting gives us `{'2', '3'}`.

Student 3
Student 3

What about difference?

Teacher
Teacher

The difference tells us what's in one set but not the other. Think of it like balancing weights. Practice this, and we’ll revisit with examples.

Student 4
Student 4

Can you summarize these operations?

Teacher
Teacher

Sure! Union combines, intersection finds common, and difference reveals exclusions. Remember, these operations follow set theory rules!

Practical Examples of Sets

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Let’s take a real-life example. If we have two sets of fruits: `fruits1 = {'apple', 'banana'}` and `fruits2 = {'banana', 'cherry'}`, what would the union be?

Student 1
Student 1

The union would be `{'apple', 'banana', 'cherry'}`!

Teacher
Teacher

Correct! Now what about the intersection?

Student 2
Student 2

The intersection would be `{'banana'}`.

Student 3
Student 3

And the difference would be `{'apple'}` from `fruits1`.

Teacher
Teacher

Perfect! Applying these operations helps manage collections easily in programming.

Introduction & Overview

Read a summary of the section's main ideas. Choose from Basic, Medium, or Detailed.

Quick Overview

Sets in Python are collections of unique elements, providing a way to manage groups of items without duplicates, along with supporting mathematical operations.

Standard

In Python, sets provide an efficient way to store collections of unique items. Unlike lists, sets automatically eliminate duplicates, making them useful in various applications where uniqueness is crucial. Sets support mathematical operations such as union, intersection, and difference, which are essential for manipulating collections of data.

Detailed

Sets in Python

Introduction: Sets are a built-in data structure in Python that offer unique functionalities pertinent for handling collections of values. They are especially useful when dealing with data that requires uniqueness and efficient membership testing.

Definition: A set is similar to a list, but it cannot contain duplicate elements. For example, creating a set from a list like ['red', 'black', 'red', 'green'] will return a set with the elements {'black', 'red', 'green'} after removing duplicates. We create an empty set using set() since the curly braces {} are used for dictionaries.

Membership Testing: You can test if an element is part of a set using the in keyword, such as if 'black' in colours:, which returns True if 'black' exists in the set.

Creating Sets from Lists and Strings: Any sequence (list, string) can be converted into a set, eliminating duplicates. For example, set([1, 3, 2, 1, 4]) results in {1, 2, 3, 4}. When a string is converted into a set, like set('banana'), it returns {'b', 'a', 'n'}.

Mathematical Operations: Python sets support essential operations mirroring those in mathematics:
- Union: Combines elements from two sets, e.g., odd.union(prime) results in {1, 2, 3, 5, 7, 9, 11}.
- Intersection: Retrieves common elements, e.g., odd & prime gives {3, 5, 7, 11}.
- Difference: Finds elements in one set but not in another, e.g., odd - prime results in {1, 9}.
- Exclusive OR (XOR): Returns elements unique to each set, e.g., odd ^ prime results in {1, 2, 9}, combining unique values from both.

Conclusion: Sets are versatile and vital structures in Python, making it easy to manage collections of unique items while providing efficient ways to perform various operations.

Youtube Videos

GCD - Euclidean Algorithm (Method 1)
GCD - Euclidean Algorithm (Method 1)

Audio Book

Dive deep into the subject with an immersive audiobook experience.

Introduction to Sets

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

A set is like a list except that you do not have duplicates. In Python, one way of writing a set is to write a list with braces like this. So, here we have associated with the name colours a list of values red, black, red and green. Notice that in setting it up, we have repeated red, but because this is a set, the duplicate red would be automatically removed.

Detailed Explanation

In Python, a set is a collection that does not allow duplicate values. This means that if you try to add the same item to a set more than once, Python will only keep it once. For instance, if you create a set called 'colours' that includes red, black, red, and green, the duplicate red will be removed automatically when you print the set. Therefore, the printed output will show only black, red, and green.

Examples & Analogies

Think of a set like a basket that can only hold one of each type of fruit. If you try to add two apples to that basket, it will only keep one apple because duplicates are not allowed. Thus, a set ensures that each type of fruitβ€”a specific color in our exampleβ€”is counted only once.

Creating Empty Sets

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

If we want to create an empty set, we have to call the set function as follows: colours = set() with no arguments.

Detailed Explanation

To create an empty set in Python, you cannot use braces like you do with dictionaries because the empty braces will create an empty dictionary instead. Instead, you must use the set() function without any arguments. For example, if you want to initialize an empty set named 'colours', you would write 'colours = set()'. This signifies that 'colours' is ready to store items without duplicates.

Examples & Analogies

Imagine you have a clean and empty chalkboard where you can write notes. You can start adding items, but initially, that chalkboardβ€”like the empty setβ€”has nothing written on it.

Membership Testing

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

Like lists and other data structures, we can test membership using in. So, if we ask whether black is in colours by using the word in, then the return value is true.

Detailed Explanation

You can check if a specific element is part of a set by using the 'in' keyword. For example, if you have a set called 'colours' containing black, red, and green, and you want to check if 'black' is in that set, you simply write 'black in colours'. If 'black' is indeed part of that set, the expression will return true; otherwise, it will return false.

Examples & Analogies

Think of it like searching for a guest's name on a guest list. You could easily check if 'Alice' is on the list by asking, 'Is Alice on this list?' If she is, you get a 'yes'; if not, a 'no'.

Creating Sets from Collections

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

We can convert any list to a set using the set function. If we give a list such as this 1, 3, 2, 1, 4 with duplicates and assign it to the name numbers, then because it’s a set the duplicate ones will be removed.

Detailed Explanation

You can take any Python list and convert it into a set using the set() function. When converting a list that has duplicate items, such as [1, 3, 2, 1, 4], the resulting set will include only unique elements: {1, 2, 3, 4}. The order of the elements in a set is arbitrary, meaning it may not maintain the order of items from the original list.

Examples & Analogies

Imagine you have a box of mixed candies where some types are duplicated. If you decide to take out only the unique types, you would end up with one of each kind, regardless of the order in which they were originally mixed.

Operations on Sets

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

Sets support basic operations like their counterparts in mathematics. For example, we can find the union of two sets, which collects all unique elements from both sets.

Detailed Explanation

Sets in Python allow you to perform basic operations like union, intersection, and difference. The union operation combines the elements from both sets without duplicates. For instance, if set A contains {1, 3, 5} and set B contains {3, 4, 5, 6}, the union A | B would give you {1, 3, 4, 5, 6}. Similarly, the intersection (&) gives only the elements common to both sets.

Examples & Analogies

Imagine two different fruit baskets: one with apples and oranges, and the other with bananas and oranges. If you combine both baskets (union), you'll end up with a collection of all types of fruit without duplicating any. If you look for fruit that is present in both baskets (intersection), you'll find only the oranges.

Set Differences and Exclusive or (XOR)

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

Set difference asks for those elements that are in odd, but not in prime. In other words, odd numbers that are not prime are examples.

Detailed Explanation

The difference operation between two sets allows you to find the elements present in one set but not in the other. For example, if set A has odd numbers {1, 3, 5, 7, 9} and set B has prime numbers {2, 3, 5, 7}, the difference A - B would yield only {1, 9}, which are the odd numbers that are not prime. There's also an exclusive or (XOR) operation, which gives the elements found in either of the two sets but not in both.

Examples & Analogies

Consider you have two sets of stickers: one set with stars, hearts, and circles (set A), and another with stars, diamonds, and triangles (set B). The difference will show you the stickers that are in set A but not in set B (hearts and circles). The XOR will show you all unique sticker types from both sets that do not overlap.

Definitions & Key Concepts

Learn essential terms and foundational ideas that form the basis of the topic.

Key Concepts

  • Sets: Unique collections of elements without duplicates.

  • Membership Test: Checking if an element exists in a set.

  • Union: Combines two sets, removing duplicates.

  • Intersection: Identifies common elements between sets.

  • Difference: Finds elements in one set that are absent in another.

Examples & Real-Life Applications

See how the concepts apply in real-world scenarios to understand their practical implications.

Examples

  • Creating a set from a list: my_set = set(['red', 'blue', 'red']) results in {'red', 'blue'}.

  • Union of two sets: set_a = {1, 2, 3} and set_b = {3, 4, 5} gives set_a.union(set_b) resulting in {1, 2, 3, 4, 5}.

Memory Aids

Use mnemonics, acronyms, or visual cues to help remember key information more easily.

🎡 Rhymes Time

  • Whenever you see a set, remember it's unique, never met. No duplications, it’s our friend, union, intersect, on it depend!

πŸ“– Fascinating Stories

  • Imagine a garden. Each flower is unique, just like a set. If a flower tries to join with a twin, it gets removed, and only one remains in the garden.

🧠 Other Memory Gems

  • U-I-D: Unique sets Incorporate Differences to remember Union, Intersection, and Difference operations.

🎯 Super Acronyms

SUIT

  • Sets Uniquely Include Things
  • reminding students of the uniqueness property of sets.

Flash Cards

Review key concepts with flashcards.

Glossary of Terms

Review the Definitions for terms.

  • Term: Set

    Definition:

    A data structure in Python that holds an unordered collection of unique elements.

  • Term: Union

    Definition:

    An operation that combines all elements from two sets, removing duplicates.

  • Term: Intersection

    Definition:

    An operation that retrieves elements common to both sets.

  • Term: Difference

    Definition:

    An operation that identifies elements in one set that are not present in another.

  • Term: Membership Test

    Definition:

    A method to check if an element exists within a set, typically using the in keyword.