Getting Started

Python - IntroductionPython - Hello World ProgramPython - SyntaxPython - Data TypesPython - Variables

Operators

Python - Arithmetic OperatorsPython - Relational OperatorsPython - Logical OperatorsPython - Assignment OperatorsPython - Bitwise OperatorsPython - Membership OperatorsPython - Identity OperatorsPython - Increment and Decrement Operators

Conditions

Python - If Else statement

Loop

Python - While LoopPython - For Loop

Numbers

Python - NumbersPython - Number Conversion

Strings

Python - StringsPython - String OperatorsPython - String FormattingPython - String MethodsPython - String Format Method

List

Python - ListPython - List Methods

Tuple

Python - Tuple

Set

Python - SetPython - Set Methods

Dictionary

Python - DictionaryPython - Dictionary Methods

Functions

Python - FunctionsPython - Functions - Variable length argumentsPython - Lambda Function

Scope of Variables

Python - Scope of Variables

Modules

Python - ModulesPython - Math ModulePython - JSON ModulePython - datetime ModulePython - time Module

I/O

Python - Read input from keyboard

File

Python - File Handling

Exception Handling

Python - Exception Handling

OOP

Python - Classes and ObjectsPython - Class Constructor __init__ methodPython - Class Destructor __del__ methodPython - Built-in Class AttributesPython - InheritancePython - Method OverridingPython - Method Overloading

Package Management

Python - PIP

Python - MySQL

Python - MySQL - Getting StartedPython - MySQL - Insert dataPython - MySQL - Select dataPython - MySQL - Update dataPython - MySQL - Delete data

Python - CSV

Python - Read data from CSV filePython - Write data in CSV file

Python - Set

Python

python logo

In this tutorial we will learn about set in Python.

We briefly talked about set in the Python - Data Type tutorial.

What is a set?

A set is an unordered unique collection of items.

We create a set in Python using curly { } brackets and separate the items using , comma.

In the following example we are creating a set of integer values.

mySet = {1, 2, 3}

The set() constructor

We use the set() constructor to create a set in Python.

# set
mySet = set((1, 3.14, 'yusufshakeel', 1+2j, True))

print("Type of mySet:", type(mySet))
print(mySet)

Output

Type of mySet: <class 'set'>
{1, 3.14, 'yusufshakeel', (1+2j)}

Counting set items

We use the len method to count the total number of items present in a given set.

The following Python program will print the total number of items in a given set.

# set
mySet = {1, 2, 3}

print(len(mySet))   # 3

Accessing set items

Items in a set don't have any index value. So, we cannot access them using index like we do in list and tuple.

To access set items we use loop.

In the following Python program we are printing out all the items present in the given set.

# set
mySet = {1, 3.14, 'yusufshakeel', True, 1+2j}

# output
for item in mySet:
    print(item)

The above code will print the following output.

1
3.14
yusufshakeel
(1+2j)

Check existence of set item

To check if an item exists in a given set we take help of the in - membership operator.

The in operator will return True if the item exists in the set. False it it is not present.

In the following Python program we are checking if the items exists in the given set.

# set
mySet = {1, 3.14, 'yusufshakeel', True, 1+2j}

# output
print(1 in mySet)        # True
print('hello' in mySet)  # False

Changing existing set items

We cannot change items of a set once they are created.

Adding new item

We use the add method to add a new item to a given set.

In the following Python program we are adding new item to a set.

# set
mySet = {1, 2, 3}

# add
mySet.add('Hello')

# output
print(mySet)

The above code will print a similar output.

{1, 2, 3, 'Hello'}

Adding multiple items

We use the update method to add multiple items to a given set.

In the following Python program we are adding multiple items to the set.

# set
mySet = {1, 2, 3}

# add multiple items
mySet.update(['yusufshakeel', 3.14, True, 1+2j])

# output
print(mySet)

We will get the following output.

{1, 2, 3.14, 3, (1+2j), 'yusufshakeel'}

Remove set items

We use the remove method to remove items from a given set.

If the item we are trying to remove does not exists then remove will raise an error.

In the following Python program we are removing items from the set.

# set
mySet = {1, 3.14, 'yusufshakeel', True, 1+2j}

# remove
mySet.remove(1+2j)

# output
print(mySet)

We will get the following output.

{1, 3.14, 'yusufshakeel'}

If the item we are trying to remove does not exists then remove will raise an error.

In the following Python program we are trying to remove an item that does not exists in the set.

# set
mySet = {1, 3.14, 'yusufshakeel', True, 1+2j}

# remove
mySet.remove('unknown')

# output
print(mySet)

We will get an error message like the following.

Traceback (most recent call last):
  File "/Users/yusufshakeel/PycharmProjects/HelloWorld/Set.py", line 5, in 
    mySet.remove('unknown')
KeyError: 'unknown'

Discard set items

To avoid having errors like the one we encountered with the remove method we use the discard method.

So, if the item does not exists in the set then the discard method will not raise any error.

In the following example we are trying to remove an item that does not exists in the set using the discard method.

# set
mySet = {1, 3.14, 'yusufshakeel', True, 1+2j}

# discard
mySet.discard('unknown')

# output
print(mySet)

On running the above code no error is raised and we get the following output.

{'yusufshakeel', 1, 3.14, (1+2j)}

Clear set items

We use the clear method to clear the items of a given set.

In the following Python program we are clearing out the items of a given set.

# set
mySet = {1, 3.14, 'yusufshakeel', True, 1+2j}

print("before", mySet)

# clear
mySet.clear()

print("after", mySet)

We will get the following output.

before {1, 3.14, 'yusufshakeel', (1+2j)}
after set()

Delete set

We use the del keyword to delete a set along with the items.

In the following Python program we are deleting a given set.

# set
mySet = {1, 3.14, 'yusufshakeel', True, 1+2j}

del mySet

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT