Python sets are an important built-in data type that represent unordered collections of unique elements. They are handy for removing duplicates and performing mathematical set operations like unions, intersections, and differences.
What is a Python Set?
A set in Python is a collection of distinct hashable objects. Unlike lists or tuples, sets are unordered and do not index elements. This makes them perfect for membership testing and eliminating duplicate entries.
Check out tutorials on the topic of Python Tuples
Creating a Set
You can create a set in Python using curly braces {} or the set() function:
# Using curly braces
fruits = {'apple', 'banana', 'cherry'}
# Using the set() function
numbers = set([1, 2, 3, 4, 5])
# Creating an empty set
# Note: {} creates an empty dictionary, not a set
empty_set = set()Set Properties
Sets in Python have several key properties:
- Unordered: Elements in a set have no specific order
- Unique Elements: Duplicates are automatically removed
- Mutable: You can add or remove elements
- Hashable Elements: Set elements must be immutable (strings, numbers, tuples)
Basic Set Operations
Adding Elements
fruits = {'apple', 'banana', 'cherry'}
fruits.add('orange') # Add a single element
fruits.update(['mango', 'grapes']) # Add multiple elementsRemoving Elements
fruits = {'apple', 'banana', 'cherry'}
fruits.remove('banana') # Raises error if element doesn't exist
fruits.discard('mango') # No error if element doesn't exist
popped_item = fruits.pop() # Removes and returns an arbitrary element
fruits.clear() # Removes all elementsMathematical Set Operations
Python sets support mathematical set operations:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Union (all elements from both sets)
union_set = set1 | set2 # or set1.union(set2)
# Intersection (elements common to both sets)
intersection_set = set1 & set2 # or set1.intersection(set2)
# Difference (elements in set1 but not in set2)
difference_set = set1 - set2 # or set1.difference(set2)
# Symmetric difference (elements in either set, but not in both)
symmetric_difference = set1 ^ set2 # or set1.symmetric_difference(set2)Set Comprehensions
Like list comprehensions, Python allows set comprehensions:
# Square of numbers from 0 to 9
squares = {x**2 for x in range(10)}
# Even numbers from a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = {x for x in numbers if x % 2 == 0}You can learn more about the topic of Python Strings
Set Methods
Here are some commonly used set methods:
| Method | Description |
|---|---|
add() | Adds an element to the set |
clear() | Removes all elements from the set |
copy() | Returns a copy of the set |
difference() | Returns the difference of two or more sets |
discard() | Removes the specified element |
intersection() | Returns the intersection of two sets |
isdisjoint() | Returns True if two sets have no intersection |
issubset() | Returns True if another set contains this set |
issuperset() | Returns True if this set contains another set |
pop() | Removes and returns an arbitrary element |
remove() | Removes the specified element |
union() | Returns the union of sets |
update() | Updates the set with elements from another set |
Common Applications of Sets
- Removing duplicates from a sequence
list_with_duplicates = [1, 2, 2, 3, 4, 4, 5]
unique_items = list(set(list_with_duplicates))- Membership testing (faster than lists for large collections)
numbers = {1, 2, 3, 4, 5}
print(3 in numbers) # True- Finding unique elements in multiple collections
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
unique_to_list1 = set(list1) - set(list2) # {1, 2}Frozen Sets
Python also provides immutable sets called frozen sets:
frozen = frozenset([1, 2, 3, 4])
# frozen.add(5) # This will raise an errorFrozen sets are hashable and can be used as keys in dictionaries or as elements in other sets.
Best Practices
- Use sets when order doesn’t matter, but uniqueness does
- Prefer sets over lists for membership testing with large collections
- Use frozen sets when you need an immutable set (like dictionary keys)
- Remember that sets can only contain hashable elements
All Python set-related Tutorials
- Remove Item from Set in Python
- Check if a Python Set is Empty
- Add Item to Set in Python
- Create an Empty Set in Python
- Compare Lists, Tuples, Sets, and Dictionaries in Python
- Python Set vs Tuple
Conclusion
Python sets are powerful data structures that provide efficient ways to handle collections of unique items and perform mathematical set operations. Their ability to eliminate duplicates and quickly check for membership makes them essential tools in a Python programmer’s toolkit.