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

Try it Yourself

Characteristics of Set Items

1. Unordered

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

Try it Yourself

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.

Try it Yourself

3. No Duplicate Values

Sets automatically remove duplicate entries.

Try it Yourself

Only unique values are stored.

Special Case: Boolean and Integer Values

In Python sets:

True is treated as 1

False is treated as 0

Try it Yourself

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.

Try it Yourself

Set Items and Data Types

A set can store elements of any data type.

Same Data Type

Try it Yourself

Mixed Data Types

Try it Yourself

Checking the Data Type of a Set

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

Try it Yourself

Output:

<class 'set'>

Using the set() Constructor

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

Try it Yourself

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.

Try it Yourself

Checking if an Item Exists in a Set

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

Try it Yourself

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.

Try it Yourself

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.

Try it Yourself

Adding Items from Another Set

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

Try it Yourself

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

Try it Yourself

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.

Try it Yourself

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

Try it Yourself

2. Using discard() (Safer Option)

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

Try it Yourself

3. Using pop() (Random Removal)

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

Try it Yourself

4. Using clear() (Empty the Set)

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

Try it Yourself

5. Using del (Delete the Set Completely)

The del keyword removes the entire set object from memory.

Try it Yourself

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.

Try it Yourself

Example

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

Try it Yourself

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.

Try it Yourself

Using the | Operator

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

Try it Yourself

Joining Multiple Sets

Using union() with Multiple Sets:

Try it Yourself

Using Multiple | Operators

Try it Yourself

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.

Try it Yourself

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.

Try it Yourself

Intersection – Keep Common Elements Only

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

Try it Yourself

Using the & Operator

Try it Yourself

intersection_update() – Modify Original Set

Try it Yourself

Boolean Values in Intersection

True equals 1, and False equals 0 in sets.

Try it Yourself

Difference – Keep Unique Items from the First Set

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

Try it Yourself

Using the - Operator

Try it Yourself

difference_update() – Modify Original Set

Try it Yourself

Symmetric Difference – Exclude Common Items

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

Try it Yourself

Using the ^ Operator

Try it Yourself

symmetric_difference_update() – Modify Original Set

Try it Yourself

Key Takeaways

  • Use union() to combine all unique elements
  • Use intersection() to find common elements
  • Use difference() to find unique elements
  • Use symmetric_difference() to exclude duplicates
  • Methods ending with _update() modify the original set

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.).

Try it Yourself

1. copy() – Create a Copy

Try it Yourself

2. union() – Combine Elements

Try it Yourself

Shortcut operator:

Try it Yourself

3. intersection() – Common Elements

Try it Yourself

Shortcut operator:

Try it Yourself

4. difference() – Unique Elements

Try it Yourself

Shortcut operator:

Try it Yourself

5. symmetric_difference() – Non-Common Element

Try it Yourself

Shortcut operator:

Try it Yourself

6. Subset and Superset Checks

Try it Yourself

Using operators:

Try it Yourself

7. isdisjoint() – No Common Elements

Try it Yourself

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.

Try it Yourself

2. clear() – Remove All Elements

Removes every item from the set, leaving it empty.

Try it Yourself

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

Returns a shallow copy of the set.

Try it Yourself

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

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

Try it Yourself

Using the operator:

Try it Yourself

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

Removes elements that are also found in another set.

Try it Yourself

6. discard() – Remove Item Without Error

Removes a specific item if it exists.

Try it Yourself

7. intersection() (&) – Common Elements

Returns a set of elements shared by all sets.

Try it Yourself

Using the operator:

Try it Yourself

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

Keeps only the elements that exist in all sets.

Try it Yourself

9. isdisjoint() – No Common Elements

Checks whether two sets share any elements.

Try it Yourself

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

Checks if all elements of one set exist in another.

Try it Yourself

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

Checks if a set contains all elements of another set.

Try it Yourself

12. pop() – Remove a Random Element

Removes and returns an arbitrary element.

Try it Yourself

13. remove() – Remove Specific Item

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

Try it Yourself

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

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

Try it Yourself

Using operator:

Try it Yourself

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

Keeps only non-common elements.

Try it Yourself

16. union() (|) – Combine Sets

Returns a set containing all unique elements.

Try it Yourself

Using operator:

Try it Yourself

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

Adds elements from another set or iterable.

Try it Yourself

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() ` `

update() ` =`



Our website uses cookies to enhance your experience. Learn More
Accept !