Python Sets

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.

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 {}.

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

Characteristics of Set Items

1. Unordered

Items in a set do not follow any specific order and cannot be accessed using an index.

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

The order of elements may differ on each execution.

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.

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

Only unique values are stored.

Special Case: Boolean and Integer Values

In Python sets:

  • True is treated as 1
  • False is treated as 0
{0, True, 'python'}

Here, True and 1 are considered duplicates, as are False and 0.

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.

Same Data Type

# Sets created successfully

Mixed Data Types

{True, 101, 75.5, 'admin'}

Checking the Data Type of a Set

From Python’s perspective, sets belong to the set class.

<class 'set'>

Using the set() Constructor

You can also create a set using the built-in set() constructor.

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

Python Collection Data Types

Python provides four main collection types:

  • List – Ordered, changeable, allows duplicates
  • Tuple – Ordered, unchangeable, allows duplicates
  • Set – Unordered, unindexed, no duplicates
  • Dictionary – Ordered, changeable, no duplicate keys

Accessing Items in a Python Set

Unlike lists or dictionaries, sets do not support indexing or keys. This is because sets are unordered and unindexed collections.

However, you can still work with set elements in two common ways:

  1. Iterating through the set
  2. Checking membership using the in keyword

Looping Through a Set

To access each item in a set, use a for loop.

pencil pen eraser

Checking if an Item Exists in a Set

You can use the in keyword to check whether a specific value is present.

True

This returns True if the item exists, otherwise False.

Checking if an Item Does NOT Exist

To confirm that an item is not in a set, use not in.

True

This returns True if the value is not present in the set.

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

To insert one new element into a set, use the add() method.

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

Adding Items from Another Set

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

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

All unique elements from tropical_fruits are added to fruits.

Adding Items from Any Iterable

The update() method accepts any iterable, not just sets. This includes lists, tuples, and even dictionary keys.

Example: Adding Items from a List

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

Key Points

  • Use add() to insert one item
  • Use update() to insert multiple items
  • update() works with sets, lists, tuples, and other iterables
  • Duplicate values are automatically ignored

Removing Items from a Python Set

Python provides several ways to remove elements from a set. The method you choose depends on whether you want error handling, random removal, or complete deletion of the set.

1. Using remove()

The remove() method deletes a specific element from the set.

{'cherry', 'apple'}

Important: If the specified item does not exist, remove() raises a KeyError.

KeyError: 'orange'

2. Using discard() (Safer Option)

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

{'cherry', 'apple'}

3. Using pop() (Random Removal)

The pop() method removes and returns a random item from the set.

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

4. Using clear() (Empty the Set)

The clear() method removes all elements, leaving an empty set.

set()

5. Using del (Delete the Set Completely)

The del keyword removes the entire set object from memory.

# Set deleted successfully

Looping Through Items in a Python Set

Since sets are unordered and unindexed, you cannot access their elements using index positions. Instead, Python allows you to iterate over set items using a for loop.

Using a for Loop with a Set

The most common way to read all elements in a set is by looping through it.

pencil pen eraser

Example

Looping through a set is useful when performing an action on every unique item.

Color available: blue Color available: green Color available: red

Key Points

  • Sets do not support indexing
  • Use a for loop to access elements
  • Output order is not guaranteed
  • Ideal for working with unique values

Joining Sets in Python

Python provides powerful set operations to combine or compare two or more sets. These operations are commonly used to find all items, common items, unique items, or non-overlapping items between sets.

Overview of Set Join Operations

  • 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

The union() method returns a new set containing all unique elements from both sets.

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

Using the | Operator

You can achieve the same result using the pipe (|) operator.

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

Joining Multiple Sets

Using union() with Multiple Sets:

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

Using Multiple | Operators

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

Joining a Set with Other Iterables

The union() method can also merge a set with lists or tuples. The | operator works only with sets, not other iterables.

{'a', 'c', 4, 5, 6, 'b'}

Update – Modify the Original Set

The update() method adds elements from another set (or iterable) directly into the original set. Unlike union(), this method does not return a new set.

{'marker', 'pencil', 'eraser', 'pen'}

Intersection – Keep Common Elements Only

The intersection() method returns elements that exist in both sets.

{'Python'}

Using the & Operator

{'Python'}

intersection_update() – Modify Original Set

{'Python'}

Boolean Values in Intersection

True equals 1, and False equals 0 in sets.

{0, 1, 'apple'}

Difference – Keep Unique Items from the First Set

The difference() method keeps elements that are only in the first set.

{'rabbit', 'cat'}

Using the - Operator

{'rabbit', 'cat'}

difference_update() – Modify Original Set

{'rabbit', 'cat'}

Symmetric Difference – Exclude Common Items

The symmetric_difference() method returns elements that are not shared between sets.

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

Using the ^ Operator

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

symmetric_difference_update() – Modify Original Set

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

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.

What Is a Frozenset?

A frozenset has the following properties:

  • Unordered – No fixed order of elements
  • Unique – Duplicate values are not allowed
  • Immutable – Items cannot be added or removed

Creating a Frozenset

You can create a frozenset using the built-in frozenset() constructor with any iterable (list, set, tuple, etc.).

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

1. copy() – Create a Copy

frozenset({1, 2, 3})

2. union() – Combine Elements

frozenset({'a', 1, 2, 'b'})

Shortcut operator:

frozenset({'a', 1, 2, 'b'})

3. intersection() – Common Elements

frozenset({'banana'})

Shortcut operator:

frozenset({'banana'})

4. difference() – Unique Elements

frozenset({1, 2})

Shortcut operator:

frozenset({1, 2})

5. symmetric_difference() – Non-Common Element

frozenset({1, 2, 4, 5})

Shortcut operator:

frozenset({1, 2, 4, 5})

6. Subset and Superset Checks

True True

Using operators:

True True

7. isdisjoint() – No Common Elements

True

Python Set Methods

Python provides a rich set of built-in methods for sets that allow you to add, remove, compare, and combine elements efficiently.

Common Set Methods with Examples

1. add() – Add One Element

Adds a single element to the set.

{'pencil', 'eraser', 'pen'}

2. clear() – Remove All Elements

Removes every item from the set, leaving it empty.

set()

3. copy() – Create a Copy of the Set

Returns a shallow copy of the set.

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

4. difference() (-) – Find Unique Elements

Returns elements that exist in the first set but not in the others.

{'cat', 'rabbit'}

Using the operator:

{'cat', 'rabbit'}

5. difference_update() (-=) – Modify the Original Set

Removes elements that are also found in another set.

{1, 2}

6. discard() – Remove Item Without Error

Removes a specific item if it exists.

{'apple', 'cherry'}

7. intersection() (&) – Common Elements

Returns a set of elements shared by all sets.

{'Python'}

Using the operator:

{'Python'}

8. intersection_update() (&=) – Modify the Original Set

Keeps only the elements that exist in all sets.

{20}

9. isdisjoint() – No Common Elements

Checks whether two sets share any elements.

True

10. issubset() (<=, <) – Subset Check

Checks if all elements of one set exist in another.

True True True

11. issuperset() (>=, >) – Superset Check

Checks if a set contains all elements of another set.

True True True

12. pop() – Remove a Random Element

Removes and returns an arbitrary element.

Removed: a Remaining: {'c', 'b'}

13. remove() – Remove Specific Item

Deletes an item but raises an error if it doesn’t exist.

{'pencil'}

14. symmetric_difference() (^) – Non-Common Elements

Returns elements that are in either set, but not in both.

{'green', 'red'}

Using operator:

{'green', 'red'}

15. symmetric_difference_update() (^=) – Modify Original Set

Keeps only non-common elements.

{1, 2, 4}

16. union() (|) – Combine Sets

Returns a set containing all unique elements.

{'y', 1, 2, 'x'}

Using operator:

{'y', 1, 2, 'x'}

17. update() (|=) – Modify Original Set

Adds elements from another set or iterable.

{'marker', 'pencil', 'eraser', 'pen'}
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 !