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)
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)
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
- Python - Check if set is empty
- Python - Check if set is not empty
- Python - Check if specified element is present in the set
- Python - Check if set contains specified element
- Python - Check if sets are equal
Set Operations
Python Set Methods
You can perform many operations on a Python Set. Following are the tutorials to these Python Set Operations.
- Python Set add()
- Python Set clear()
- Python Set copy()
- Python Set difference()
- Python Set difference_update()
- Python Set discard()
- Python Set intersection()
- Python Set intersection_update()
- Python Set isdisjoint()
- Python Set issubset()
- Python Set issuperset()
- Python Set pop()
- Python Set remove()
- Python Set symmetric_difference()
- Python Set symmetric_difference_update()
- Python Set union()
- Python Set update()
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.