Python Sets
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Python Sets

Kishore V

Python Sets

A set in Python is used to store multiple values in a single variable. It is one of Python’s four built-in collection data types, along with List, Tuple, and Dictionary—each designed for different use cases.

What Is a Set?

A set is a collection that is:

  • Unordered – Items have no fixed position
  • Unindexed – Elements cannot be accessed by index
  • Unchangeable – Individual items cannot be modified
  • Unique – Duplicate values are not allowed

Although set items themselves cannot be changed, you can add new items or remove existing ones.

Creating a Set

Sets are written using curly braces {}.

{'orange', 'mango', 'grapes'}

Characteristics of Set Items

1. Unordered

Items in a set do not follow any specific order and cannot be accessed using an index. The order of elements may differ on each execution.

{'green', 'red', 'blue'}

2. Unchangeable (Immutable Items)

Once a set is created, you cannot change its elements directly. However, you can remove or add items.

{1, 3, 4}

3. No Duplicate Values

Sets automatically remove duplicate entries. Only unique values are stored.

{'Chennai', 'Delhi', 'Mumbai'}

Special Case: Boolean and Integer Values

In Python sets: True is treated as 1, and False is treated as 0.

{0, True, 'python'}

Finding the Length of a Set

Use the len() function to get the number of elements in a set.

3

Set Items and Data Types

A set can store elements of any data type, including mixed data types.

{True, 'admin', 101, 75.5}

Checking the Data Type of a Set

<class 'set'>

Using the set() Constructor

{'cat', 'dog', 'rabbit'}

Accessing Items in a Python Set

Unlike lists or dictionaries, sets do not support indexing or keys. However, you can still work with set elements by iterating through the set or checking membership using the in keyword.

Looping Through a Set

pencil eraser pen

Checking if an Item Exists in a Set

True

Checking if an Item Does NOT Exist

True

Adding Items to a Python Set

In Python, set elements themselves cannot be modified, but you can still add new items or merge items from other collections after the set is created.

Adding a Single Item

{'cherry', 'apple', 'orange', 'banana'}

Adding Items from Another Set

To combine elements from one set into another, use the update() method.

{'mango', 'cherry', 'apple', 'pineapple', 'papaya', 'banana'}

Adding Items from Any Iterable

{'kiwi', 'cherry', 'apple', 'orange', 'banana'}

Removing Items from a Python Set

1. Using remove()

{'cherry', 'apple'}

2. Using discard() (Safer Option)

The discard() method also removes an element, but does not raise an error if the item is missing.

{'cherry', 'apple'}

3. Using pop() (Random Removal)

Removed: cherry Remaining: {'apple', 'banana'}

4. Using clear() and del

set()

Joining Sets in Python

Python provides powerful set operations to combine or compare two or more sets.

Method Purpose
union() Combines all unique elements
update() Adds elements to an existing set
intersection() Keeps only common elements
difference() Keeps elements unique to the first set
symmetric_difference() Keeps elements not common to both sets

Union – Combine All Elements

Returns a new set containing all unique elements from both sets. The | operator does the exact same thing.

{'blue', 'red', 'green', 20, 10, 30} {'blue', 'red', 'green', 20, 10, 30}

Joining Multiple Sets

{1, 2, 'bike', 'x', 'Alice', 'car', 'Bob', 'y'} {1, 2, 'bike', 'x', 'Alice', 'car', 'Bob', 'y'}

Intersection – Keep Common Elements Only

The intersection() method returns elements that exist in both sets. You can use the & operator as a shortcut.

{'Python'} {'Python'}

Difference – Keep Unique Items from the First Set

Returns elements that exist in the first set but not in the second. The shortcut is the - operator.

{'rabbit', 'cat'} {'rabbit', 'cat'}

Symmetric Difference – Exclude Common Items

Returns elements that are not shared between sets. The shortcut is the ^ operator.

{'Diana', 'Alice', 'Charlie'} {'Diana', 'Alice', 'Charlie'}

Python frozenset

A frozenset is an immutable (unchangeable) version of a set. It behaves much like a normal set, but once created, its elements cannot be modified.

frozenset({'eraser', 'pen', 'pencil'}) <class 'frozenset'>

Even though frozensets are immutable, they support all non-modifying set operations like union(), intersection(), difference(), and symmetric_difference().

Subset, Superset, and Disjoint Checks

True True True

Python Set Methods Summary

Method Operator Purpose
add() Add one element
clear() Remove all elements
copy() Copy set
difference() - Unique elements
difference_update() -= Modify original
discard() Remove safely
intersection() & Common elements
intersection_update() &= Modify original
isdisjoint() No common items
issubset() <=, < Subset check
issuperset() >=, > Superset check
pop() Remove random item
remove() Remove item
symmetric_difference() ^ Non-common items
symmetric_difference_update() ^= Modify original
union() | Combine sets
update() |= Modify original
Our website uses cookies to enhance your experience. Learn More
Accept !