← Back to list

Python Sets

Shravya · 2024-12-11 06:06 · 0 claps · 3.1 min read
#python-programming #data-structures #set #methods #python
Open on Medium ↗
Wiki topics: 💻 · Programming

Python Sets

In Python, a set is a versatile and essential data structure that provides a unique and unordered collection of elements.

Sets are particularly powerful for scenarios requiring operations like union, intersection, or difference, commonly found in mathematics and data analysis. They simplify tasks like eliminating duplicate values, checking membership, and performing efficient comparisons between datasets.

With their distinct properties and a range of built-in methods, Python sets offer a balance of simplicity and utility, making them an indispensable tool for both beginners and experienced developers.

A set is an unordered, mutable collection that ensures all its elements are unique. Sets are defined using curly braces {} or the set() function.

Key Characteristics of Sets

  1. Unordered: The items in a set do not have a defined order.
  2. Mutable: You can add or remove items from a set.
  3. Unique Elements: A set automatically removes duplicate items.

Defining a Set

# Using curly braces
fruits = {"apple", "banana", "cherry"}
print(fruits)  # Output may vary as sets are unordered
# Using the set() function
numbers = set([1, 2, 3, 2])
print(numbers)  # Output: {1, 2, 3}
# Empty set
empty_set = set()
print(empty_set)  # Output: set()

Basic Operations with Sets

Adding Elements

Use add() to add a single element and update() to add multiple elements.

my_set = {1, 2, 3}
my_set.add(4)
print(my_set)  # Output: {1, 2, 3, 4}
my_set.update([5, 6])
print(my_set)  # Output: {1, 2, 3, 4, 5, 6}

Removing Elements

Use remove() or discard() to remove elements. The difference is that remove() raises an error if the element is not found, while discard() does not.

my_set = {1, 2, 3}
my_set.remove(2)
print(my_set)  # Output: {1, 3}
my_set.discard(4)  # No error even if 4 is not in the set
print(my_set)  # Output: {1, 3}

Set Membership

Check if an item is in a set using the in keyword.

my_set = {"apple", "banana", "cherry"}
print("apple" in my_set)  # Output: True
print("orange" in my_set)  # Output: False

Set Methods (Mathematical Operations)

  1. Union (| or union()): Combines all unique items from two sets.
  2. Intersection (& or intersection()): Returns items common to both sets.
  3. Difference (- or difference()): Items in the first set but not in the second.
  4. Symmetric Difference (^ or symmetric_difference()): Items in either set but not both.
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B)  # Union: {1, 2, 3, 4, 5}
print(A & B)  # Intersection: {3}
print(A - B)  # Difference: {1, 2}
print(A ^ B)  # Symmetric Difference: {1, 2, 4, 5}

Other Useful Methods

  • clear(): Removes all elements from the set.
  • copy(): Returns a shallow copy of the set.
  • isdisjoint(): Checks if two sets have no common elements.
  • issubset(): Checks if one set is a subset of another.
  • issuperset(): Checks if one set is a superset of another.
A = {1, 2}
B = {1, 2, 3}
print(A.issubset(B))  # Output: True
print(B.issuperset(A))  # Output: True

Immutable Sets: frozenset

frozenset is an immutable version of a set. Once created, its elements cannot be modified.

frozen = frozenset([1, 2, 3])
print(frozen)  # Output: frozenset({1, 2, 3})
# Attempting to modify it will raise an error
# frozen.add(4)  # AttributeError: 'frozenset' object has no attribute 'add'

Use Cases of Sets in Python

Removing Duplicates

items = [1, 2, 3, 2, 4, 1] 
unique_items = set(items) 
print(unique_items)  # Output: {1, 2, 3, 4}

Membership Testing Sets offer O(1) time complexity for membership checks, making them faster than lists.

nums = {1, 2, 3, 4} 
print(5 in nums)  # Output: False

Set Operations for Data Analysis Useful in finding overlaps or differences between datasets.

dataset1 = {"apple", "banana", "cherry"} 
dataset2 = {"banana", "cherry", "date"}  
common_items = dataset1 & dataset2 
print(common_items)  # Output: {'banana', 'cherry'}

Efficient Lookups Sets can be used to filter or find items in a large dataset.

Advantages of Python Sets

  • Efficiency: Fast membership testing and insertion/deletion due to hash tables.
  • Simplicity: Easy-to-use methods for common operations.
  • Versatility: Ideal for problems involving unique elements or set-based operations.

Limitations

  • Sets are unordered, so elements cannot be indexed.
  • Elements must be immutable (e.g., no lists or dictionaries).

Time and Space compelexity for Set and its methods

Sets are implemented as hash tables, so their space complexity is proportional to the number of elements, i.e., O(n). Due to hashing, additional memory is required for storing the hash table and handling collisions.


메타데이터
post_id
d9629be7d660
slug
python-sets-d9629be7d660
url
https://medium.com/@shras_a/python-sets-d9629be7d660
canonical_url
https://medium.com/@shras_a/python-sets-d9629be7d660
author_url
https://medium.com/@shras_a
status
ok
fetched_at
2026-07-21 17:06:49