Completed
-
1. Introduction to Python
-
2. Python Basics
-
3. Working with Data Structures
-
4. Functions and Modules
-
5. Object-Oriented Programming (OOP)
-
6. File Handling
-
7. Error and Exception Handling
-
8. Python for Data Analysis
-
9. Advanced Topics in Python
-
10. Working with APIs
-
11. Python for Automation
-
12. Capstone Projects
- 13. Final Assessment and Quizzes
3.4 Sets
In Python, sets are a collection of unordered, unique elements. A set is similar to a list or a dictionary but does not allow duplicate values. Sets are commonly used when you need to store multiple items and want to ensure there are no duplicates.
1. What is a Set?
A set is an unordered collection of unique elements. The elements in a set are not indexed and cannot be accessed via an index or key, unlike lists or dictionaries. A set is useful when you need to store distinct values and perform set operations like union, intersection, and difference.
2. Creating a Set
You can create a set in Python using curly braces {} or the built-in set() function.
Examples:
# Creating a set using curly braces my_set = {1, 2, 3, 4, 5} print(my_set) # Output: {1, 2, 3, 4, 5} # Creating a set using the set() function another_set = set([1, 2, 3, 4, 5]) print(another_set) # Output: {1, 2, 3, 4, 5}
- A set does not allow duplicate elements. If you try to add duplicates, they will be ignored.
duplicate_set = {1, 2, 2, 3, 4} print(duplicate_set) # Output: {1, 2, 3, 4} (duplicates removed)
3. Accessing Elements in a Set
Since sets are unordered, they do not support indexing, slicing, or other sequence-like behavior. However, you can iterate over a set using loops (e.g., for loop).
Example:
# Iterating through a set for element in my_set: print(element)
This will print each element in the set, but the order is not guaranteed.
4. Modifying a Set
Sets are mutable, meaning you can add or remove elements after they have been created.
Adding Elements:
You can add individual elements to a set using the add() method.
# Adding an element to a set my_set.add(6) print(my_set) # Output: {1, 2, 3, 4, 5, 6}
To add multiple elements at once, use the update() method.
# Adding multiple elements my_set.update([7, 8, 9]) print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9}
Removing Elements:
You can remove elements from a set using remove() or discard(). The remove() method raises an error if the element is not found, while discard() will not raise an error.
# Removing an element my_set.remove(5) # Removes 5 print(my_set) # Output: {1, 2, 3, 4, 6, 7, 8, 9} # Discarding an element (no error if not found) my_set.discard(10) # 10 is not in the set, so no error print(my_set) # Output: {1, 2, 3, 4, 6, 7, 8, 9}
If you want to remove and return an arbitrary element, use pop(). This is particularly useful when you don't care about which element is removed.
# Removing and returning an arbitrary element element = my_set.pop() print(element) # Outputs the popped element print(my_set) # Output: remaining elements in the set
To clear all elements in a set, use the clear() method.
# Clearing all elements my_set.clear() print(my_set) # Output: set() (empty set)
5. Set Operations
Python sets support several powerful operations, allowing you to perform various mathematical set operations such as union, intersection, difference, and symmetric difference.
Union (|)
The union of two sets is a set containing all elements from both sets, without duplicates.
set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1 | set2 print(union_set) # Output: {1, 2, 3, 4, 5}
Intersection (&)
The intersection of two sets is a set containing only the elements that are present in both sets.
set1 = {1, 2, 3} set2 = {3, 4, 5} intersection_set = set1 & set2 print(intersection_set) # Output: {3}
Difference (-)
The difference of two sets is a set containing elements that are in the first set but not in the second.
set1 = {1, 2, 3} set2 = {3, 4, 5} difference_set = set1 - set2 print(difference_set) # Output: {1, 2}
Symmetric Difference (^)
The symmetric difference of two sets is a set containing elements that are in either of the sets, but not in both.
set1 = {1, 2, 3} set2 = {3, 4, 5} symmetric_difference_set = set1 ^ set2 print(symmetric_difference_set) # Output: {1, 2, 4, 5}
6. Set Membership
You can check if an element is a member of a set using the in keyword.
# Checking membership print(3 in my_set) # Output: True print(10 in my_set) # Output: False
7. Set Comprehension
Just like list comprehension, you can create sets using set comprehension. This provides a concise way to create sets based on existing iterables or conditions.
Example of set comprehension:
# Creating a set of squares of numbers squares = {x**2 for x in range(5)} print(squares) # Output: {0, 1, 4, 9, 16}
8. Use Cases of Sets
Sets are useful in scenarios where:
- Unique elements are required (e.g., eliminating duplicates from a collection of data).
- Mathematical set operations (such as union, intersection, etc.) need to be performed efficiently.
- Fast membership testing is needed (i.e., checking if an item exists in a collection).
- Removing duplicates from a list or another iterable.
Summary of Sets in Python
- Unordered collection of unique elements.
- Supports set operations like union, intersection, difference, and symmetric difference.
- Provides methods for adding, removing, and updating elements.
- Allows efficient membership testing and is useful for mathematical and logical set operations.
Sets are a versatile data structure in Python, useful for handling collections of unique items and performing set-based operations.
Commenting is not enabled on this course.