Python Sets
Python Sets
A set in Python is an unordered collection of unique elements. Sets are mutable, meaning you
can add or remove elements, but their elements must be immutable (e.g., integers, strings,
tuples). Sets are particularly useful for membership testing and eliminating duplicate entries.
Creating a Set
You can create a set using the set() constructor or curly braces {}.
Example:
python
Copy code
# Creating a set with curly braces
fruits = {"apple", "banana", "cherry"}
print(fruits) # Output: {'apple', 'banana', 'cherry'}
Characteristics of Sets
1. Adding Elements
python
Copy code
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits) # Output: {'apple', 'banana', 'cherry'}
2. Updating Elements
python
Copy code
fruits = {"apple", "banana"}
fruits.update(["cherry", "orange"])
print(fruits) # Output: {'apple', 'banana', 'cherry', 'orange'}
3. Removing Elements
remove(): Removes a specific element; raises an error if the element does not exist.
discard(): Removes a specific element; does not raise an error if the element does not
exist.
pop(): Removes a random element.
clear(): Empties the set.
python
Copy code
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana") # Removes 'banana'
print(fruits) # Output: {'apple', 'cherry'}
4. Set Membership
python
Copy code
fruits = {"apple", "banana", "cherry"}
print("apple" in fruits) # Output: True
print("orange" not in fruits) # Output: True
1. Union
python
Copy code
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
2. Intersection
python
Copy code
print(set1.intersection(set2)) # Output: {3}
3. Difference
python
Copy code
print(set1.difference(set2)) # Output: {1, 2}
4. Symmetric Difference
python
Copy code
print(set1.symmetric_difference(set2)) # Output: {1, 2, 4, 5}
Set Comprehension
Like list comprehensions, sets support comprehensions for generating new sets.
Example:
python
Copy code
squared = {x ** 2 for x in range(5)}
print(squared) # Output: {0, 1, 4, 9, 16}
python
Copy code
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers) # Output: {1, 2, 3, 4, 5}
2. Membership Testing
python
Copy code
names = {"Alice", "Bob", "Charlie"}
if "Bob" in names:
print("Bob is in the set!") # Output: Bob is in the set!
3. Set Algebra For operations like finding common employees in two departments or
differences in datasets.
Summary
Use sets when you need to maintain unique elements and perform mathematical
operations.
Sets are unordered and mutable but do not support indexing.
Python provides several built-in methods to manipulate sets, making them powerful for
many use cases.