Python Set add()

Python Set add() method

Python Set add() method adds given element to the set.

In this tutorial, you will learn how to use Python Set add() method, with syntax and different usage scenarios, with example programs.

Syntax of Set clear()

The syntax to call add() method on a set is

set.add(element)

Parameters

Set add() method takes one parameter.

ParameterDescription
elementRequired
Any valid Python object.
This object is added to the set.
Python Set add() method parameters table

Return value

add() method returns None.

Examples

1. Adding an element ‘g’ to Set in Python

In this example, we shall add an element to the set. The element we are adding, is not already present in the set.

Python Program

# Take a set
set_1 = {'a', 'b', 'c'}

# Add element to set
set_1.add('g')

print(set_1)
Run Code Copy

Output

{'g', 'c', 'a', 'b'}

2. Adding a duplicate element to the Set in Python

In this example, we shall pass a duplicate element, element that is already present in the set, to add() method. The resulting set should be unchanged because set can have only unique elements.

Python Program

# Initialize set
set_1 = {'a', 'b', 'c'}

# Add() method with duplicate element
set_1.add('c')

print(set_1)
Run Code Copy

Output

{'c', 'a', 'b'}

The resulting set is unchanged. The elements of the original set and modified set are same.

Summary

In this Python Set Tutorial, we learned how to use add() method to add elements to a set, with the help of well detailed Python programs.

Code copied to clipboard successfully 👍