Python Sets

Python Set

Python Set is a collection of elements.

Elements of a Python Set are unordered. There is no indexing mechanism in which you can access the elements of a Set.

Python Set elements are unique. You cannot have two elements with same reference or value in a set.

Python Set is mutable. You can change/modify the elements in a Set.

Initialize a Set

You can initialize a Python Set using flower braces {}. Elements you would like initialize in the set go inside these braces. If there are multiple elements, they should be separated from each other using comma.

Following is a simple example, demonstrating the initialization of an empty set, set with single element, and set with multiple elements.

Python Program

# Empty set
set_1 = {}

# Set with single item
set_2 = {54}

# Set with multiple items
set_3 = {32, 41, 29, 85}

print(set_1)
print(set_2)
print(set_3)
Run Code Copy

Output

{}
{54}
{32, 41, 85, 29}

Set can have only Unique Values

We already mentioned that elements of Python Set should be unique.

In this example, let us try to initialize a Python Set with some duplicate elements and observe what happens.

Python Program

# Set with duplicate items
set_3 = {32, 41, 29, 41, 32, 85}

print(set_3)
Run Code Copy

Output

{32, 41, 85, 29}

Only unique elements are initialized to the set and the duplicates are discarded.

Python Set Tutorials

The following tutorials cover some of the typical use cases related to sets in Python.

Basics

Checks

Set Operations

Python Set Methods

You can perform many operations on a Python Set. Following are the tutorials to these Python Set Operations.

Summary

In this tutorial of Python Examples, we learned what a Python Set is, how to initialize it, and different methods available to apply on a Python Set.

Related Tutorials

Code copied to clipboard successfully 👍