Python Sets
Introduction to Sets in Python
In Python, a set is an unordered collection of unique elements. Sets are defined by enclosing elements in curly braces {}
or by using the set()
constructor. Here are some key features and operations related to Python sets:
1. Creating Sets:
# Using curly braces
fruits = {'apple', 'banana', 'orange'}
# Using set() constructor
numbers = set([1, 2, 3, 4, 5])
2. Set Operations:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union_set = set1 | set2 # Union
intersection_set = set1 & set2 # Intersection
difference_set = set1 - set2 # Difference
symmetric_difference_set = set1 ^ set2 # Symmetric Difference
3. Adding and Removing Elements:
numbers = {1, 2, 3}
numbers.add(4) # Add element
numbers.remove(2) # Remove element (raises an error if not present)
numbers.discard(3) # Remove element (ignores if not present)
4. Set Methods:
numbers = {1, 2, 3, 4}
numbers.add(5)
numbers.remove(3)
numbers.clear()
5. Checking Membership:
fruits = {'apple', 'banana', 'orange'}
has_apple = 'apple' in fruits # True
has_mango = 'mango' not in fruits # True
6. Set Comprehension:
squares_set = {x**2 for x in range(5)}
7. Frozen Sets:
frozen_numbers = frozenset([1, 2, 3, 4, 5])
Sets are useful for tasks that involve testing membership, eliminating duplicate entries, and performing set operations. However, sets do not maintain the order of elements. If order is important, you may want to use a different collection type, such as a list or tuple.