Open In App

Set add() Method in Python

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Python set add() method adds a given element to a set if the element is not present in the set in Python.

Example: Add Element to an Empty set

It is used to add a new element to the empty set.

Python3




GEEK = set()
GEEK.add('s')
print("Letters are:", GEEK)
 
# adding 'e' again
GEEK.add('e')
print("Letters are:", GEEK)
# adding 's' again
GEEK.add('s')
print("Letters are:", GEEK)


Output

Letters are: {'s'}
Letters are: {'e', 's'}
Letters are: {'e', 's'}

Set add() Syntax

Syntax: set.add( elem )

Parameters

  • elem: The element that needs to be added to a set.

Return

The add() method does not return anything 

What is set add() Method

In Python, a set is an unordered collection of unique elements. The add() method is a built-in method in Python that is used to add a single element to a set. If the element is already present in the set, the set remains unchanged.

Python Set add() Method Examples

Before going to the example we are assuming the time complexity of the set.add() function is O(1) because the set is implemented using a hash table.

Now let’s look at some use cases of add() function in Python with examples:

  • Add Element to an Empty set
  • Add a new element to a Python set
  • Add an element in a set that already exists
  • Adding any iterable to a set

1. Add Element to an Empty set

It is used to add a new element to the empty set.

Python3




GEEK = set()
GEEK.add('s')
print("Letters are:", GEEK)
 
# adding 'e' again
GEEK.add('e')
print("Letters are:", GEEK)
# adding 's' again
GEEK.add('s')
print("Letters are:", GEEK)


Output

Letters are: {'s'}
Letters are: {'e', 's'}
Letters are: {'e', 's'}

2. Add a new element to a Python set

It is used to add a new element to the set if it is not existing in a set.

Python3




# set of letters
GEEK = {'g', 'e', 'k'}
 
# adding 's'
GEEK.add('s')
print("Letters are:", GEEK)
 
# adding 's' again
GEEK.add('s')
print("Letters are:", GEEK)


Output:

Letters are: {'e', 's', 'g', 'k'}
Letters are: {'e', 's', 'g', 'k'}

3. Add element in a set that already exists

It is used to add an existing element to the set if it is existing in the Python set and check if it gets added or not.

Python3




# set of letters
GEEK = {6, 0, 4}
 
# adding 1
GEEK.add(1)
print('Letters are:', GEEK)
 
# adding 0
GEEK.add(0)
print('Letters are:', GEEK)


Output:

Letters are: {0, 1, 4, 6}
Letters are: {0, 1, 4, 6}

4. Adding any iterable to a set

We can add any Python iterable to a set using Python add or Python update function, if we try to add a list using the add function we get an unhashable Type error.

Python3




# Python code to demonstrate addition of tuple to a set.
s = {'g', 'e', 'e', 'k', 's'}
t = ('f', 'o')
l = ['a', 'e']
 
# adding tuple t to set s.
s.add(t)
 
# adding list l to set s.
s.update(l)
 
print(s)


Output :

{'a', 'g', 'k', 'e', ('f', 'o'), 's'}

In this article we covered the add() function in Python. Set add() method in Python is useful to avoid entry of duplicate item in the set.

Read More on Set Methods



Previous Article
Next Article

Similar Reads

Python PIL | ImageChops.add() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageChops module contains a number of arithmetical image operations, called channel operations (“chops”). These can be used for various purposes, including special effects, image compositions, algorithmic painting, and more. PIL.ImageChops.
2 min read
Python | sympy.Add() method
With the help of sympy.Add() method, we can add two variables and can form a mathematical expression by using sympy.Add() method. Syntax : sympy.Add() Return : Return the addition of two variables. Example #1 : In this example we can see that by using sympy.Add() method, we are able to add the two variables and we can also form mathematical express
1 min read
Python | sympy.Add() method
With the help of sympy.Add() method, we can add the two variables and can form a mathematical expression by using sympy.Add() method. Syntax : sympy.Add() Return : Return the addition of two variables. Example #1 : In this example we can see that by using sympy.Add() method, we are able to add the number of variables and can form a mathematical exp
1 min read
Python - PyTorch add() method
PyTorch torch.add() method adds a constant value to each element of the input tensor and returns a new modified tensor. Syntax: torch.add(inp, c, out=None) Arguments inp: This is input tensor. c: The value that is to be added to every element of tensor. out: This is optional parameter and it is the output tensor. Return: It returns a Tensor. Let's
1 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Python3 Program to Split the array and add the first part to the end | Set 2
Given an array and split it from a specified position, and move the first part of array add to the end.   Examples:   Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : Split from index 2 and first part {12, 10} add to the end . Input : arr[] = {3, 1, 2} k = 1 Output : arr[] = {1, 2, 3} Explanation :
2 min read
Add A Dictionary To A `Set()` With Union
In Python, there is a powerful data structure called set(), which is an unordered collection of unique elements. In this article, we will learn how to add a dictionary to a set() using the union method. This can be particularly useful when you want to combine unique key-value pairs from different dictionaries into a single set. Before we dive into
3 min read
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Python - Add values to Dictionary of List
In this article, we will discuss how to add values to the dictionary of lists. We can add values to a dictionary by using a list, the input list would be the following structure: [('key',value),...........,('key',value)] So the above list is an input, which we can use with for loop to add values to the dictionary of lists. Syntax: for key, value in
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg