Python Sets - Python Guides (2025)

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 bracesfruits = {'apple', 'banana', 'cherry'}# Using the set() functionnumbers = set([1, 2, 3, 4, 5])# Creating an empty set# Note: {} creates an empty dictionary, not a setempty_set = set()

Set Properties

Sets in Python have several key properties:

  1. Unordered: Elements in a set have no specific order
  2. Unique Elements: Duplicates are automatically removed
  3. Mutable: You can add or remove elements
  4. 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 elementfruits.update(['mango', 'grapes']) # Add multiple elements

Removing Elements

fruits = {'apple', 'banana', 'cherry'}fruits.remove('banana') # Raises error if element doesn't existfruits.discard('mango') # No error if element doesn't existpopped_item = fruits.pop() # Removes and returns an arbitrary elementfruits.clear() # Removes all elements

Mathematical 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 9squares = {x**2 for x in range(10)}# Even numbers from a listnumbers = [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:

MethodDescription
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

  1. Removing duplicates from a sequence
 list_with_duplicates = [1, 2, 2, 3, 4, 4, 5] unique_items = list(set(list_with_duplicates))
  1. Membership testing (faster than lists for large collections)
 numbers = {1, 2, 3, 4, 5} print(3 in numbers) # True
  1. 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 error

Frozen sets are hashable and can be used as keys in dictionaries or as elements in other sets.

Best Practices

  1. Use sets when order doesn’t matter, but uniqueness does
  2. Prefer sets over lists for membership testing with large collections
  3. Use frozen sets when you need an immutable set (like dictionary keys)
  4. 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.

Python Sets - Python Guides (2025)

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Trent Wehner

Last Updated:

Views: 6150

Rating: 4.6 / 5 (76 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Trent Wehner

Birthday: 1993-03-14

Address: 872 Kevin Squares, New Codyville, AK 01785-0416

Phone: +18698800304764

Job: Senior Farming Developer

Hobby: Paintball, Calligraphy, Hunting, Flying disc, Lapidary, Rafting, Inline skating

Introduction: My name is Trent Wehner, I am a talented, brainy, zealous, light, funny, gleaming, attractive person who loves writing and wants to share my knowledge and understanding with you.