The Wayback Machine - https://web.archive.org/web/20240828175358/https://www.geeksforgeeks.org/set-add-python/
Open In App

Set add() Method in Python

Last Updated : 08 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Python
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.

Python
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.

Python
# 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.

Python
# 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.

Python
# 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

Set add() Method in Python – FAQs

How to Use the add() Method with Sets in Python?

The add() method in Python is used to add a single element to a set. If the element is already present, it does nothing as sets do not allow duplicate elements.

Example:

# Creating a set
my_set = {1, 2, 3}

# Adding a new element to the set
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}

# Adding an existing element to the set
my_set.add(3)
print(my_set) # Output: {1, 2, 3, 4} (no change since 3 is already in the set)

How to Add Elements to a Set in Python?

You can add elements to a set using the add() method for single elements or the update() method for multiple elements.

Using add() Method:

my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}

Using update() Method:

my_set = {1, 2, 3}
my_set.update([4, 5, 6])
print(my_set) # Output: {1, 2, 3, 4, 5, 6}

What is the Difference Between add() and update() in Sets?

my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}

add() Method: Adds a single element to the set. If the element already exists, it does nothing.

update() Method: Adds multiple elements to the set. It can take any iterable as an argument (e.g., lists, tuples, sets).

my_set = {1, 2, 3}
my_set.update([4, 5, 6])
print(my_set) # Output: {1, 2, 3, 4, 5, 6}

What Happens When an Existing Item is Added to a Set in Python?

When an existing item is added to a set using the add() method, nothing changes. Sets automatically handle duplicates by ignoring any element that is already present.

Example:

my_set = {1, 2, 3}
my_set.add(3)
print(my_set) # Output: {1, 2, 3} (no change since 3 is already in the set)

Are Sets Ordered in Python?

No, sets are unordered collections in Python. This means that the items have no defined order, and you cannot rely on the order of elements when you iterate over a set or print it.

Example:

my_set = {3, 1, 2}
print(my_set) # Output: {1, 2, 3} or any other permutation (the order is not guaranteed)


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
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
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 packages to Anaconda environment in Python
Let's see some methods that can be used to install packages in the Anaconda environment. There are many ways one can add pre-built packages to an anaconda environment. So, let's see how to direct the path in the anaconda and install them. Add packages to the Anaconda environment using the navigator Step 1: Open your Anaconda navigator Step 2: Go to
2 min read
Python | Pandas Series.add()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Python Series.add() is used to add series or list like objects with same length to the caller series. Syntax: Series.add(other, level=No
2 min read
Python | Pandas dataframe.add()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Dataframe.add() method is used for addition of dataframe and other, element-wise (binary operator add). Equivalent to dataframe + other,
3 min read
numpy.defchararray.add() in Python
numpy.core.defchararray.add(arr1, arr2): Concatenates two strings element-wise. Parameters: arr1 : array-like or string. arr2 : array-like or string. Returns : Concatenates String. Code #1: # Python Program illustrating # numpy.char.add() method import numpy as np arr1 = ['vdteteAAAa', 'AAAttttds', 'AAaxtt'] arr2 = ['1111sfdsf', '1111111sdsf2', '11
1 min read
Python | Pandas Panel.add()
In Pandas, Panel is a very important container for three-dimensional data. The names for the 3 axes are intended to give some semantic meaning to describing operations involving panel data and, in particular, econometric analysis of panel data. In Pandas Panel.add() function is used for element-wise addition of series and series/dataframe. Syntax:
2 min read
Python | Ways to add row/columns in numpy array
Given a Numpy array, the task is to add rows/columns basis on requirements to the Numpy array. Let's see a few examples of this problem in Python. Add columns in the Numpy arrayMethod 1: Using np.append() C/C++ Code import numpy as np ini_array = np.array([[1, 2, 3], [45, 4, 7], [9, 6, 10]]) # printing initial array print("initial_array :
5 min read
Python | Add style to tkinter button
Tkinter is a Python standard library that is used to create GUI (Graphical User Interface) applications. It is one of the most commonly used packages of Python. Tkinter supports both traditional and modern graphics support with the help of Tk themed widgets. All the widgets that Tkinter also has available in tkinter.ttk.Adding style in a tkinter.tt
4 min read
Python Tkinter | Create LabelFrame and add widgets to it
Tkinter is a Python module which is used to create GUI (Graphical User Interface) applications. It is a widely used module which comes along with the Python. It consists of various types of widgets which can be used to make GUI more user-friendly and attractive as well as functionality can be increased. LabelFrame can be created as follows: -> i
2 min read
Python | Add image on a Tkinter button
Tkinter is a Python module which is used to create GUI (Graphical User Interface) applications with the help of varieties of widgets and functions. Like any other GUI module it also supports images i.e you can use images in the application to make it more attractive. Image can be added with the help of PhotoImage() method. This is a Tkinter method
3 min read
Python | Add Label to a kivy window
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, iOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications.Label widget - The Label widget is for rendering text. It supports ASCII and unicode strings. The label is the text
4 min read
Python | Add image widget in Kivy
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. 👉🏽 Kivy Tutorial - Learn Kivy with Examples. Image Widget: The Image widget is used to display an
4 min read
Python | Add element at alternate position in list
Sometimes, while working with Python list, we can have a problem in which we need to add elements in list alternatively i.e at even positions and reorder the list accordingly. This has a potential application in many domains such as day-day programming and competitive programming. Let's discuss certain way in which this problem can be solved. Metho
2 min read
Python - Add audio files in kivy
Kivy is a platform independent GUI tool in Python. Kivy is a tool used to build cross-platform applications in Python which can run on android, IOS, Linux, Windows. Audio Widget: This module is used to load audio files in kivy. from kivy.core.audio import SoundLoader Below is the code on how you can import an audio file in kivy. NOTE:You can import
1 min read
Extract numbers from a text file and add them using Python
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Data file handling in Python is done in two types of files: Text file (.txt extension) Binary file (.bin extension) Here we are operating on the .txt file in Python. Through this program
4 min read
Add QT GUI to Python for plotting graphics
Qt framework (with QT Creator IDE) can be used to create a fancy interfaces for Python GUI application. Plotting graphics on a GUI is possible with pyqtgraph library. Installing pyqtgraph - There are several ways of installing pyqtgraph depending on your needs. If you are using Anaconda you can install with: conda install -c anaconda pyqtgraph Or w
2 min read
Add a User in Linux using Python Script
Creating a user via command line in Linux is a tedious task. Every time someone joins your organization and you need to type a long Linux command rather than doing this you can create a python script that can ask for you the username and password and create that user for you. Examples: Input : Enter Username : John Password: **** Output : User succ
1 min read
How to add one polynomial to another using NumPy in Python?
In this article, Let's see how to add one polynomial to another. Two polynomials are given as input and the result is the addition of two polynomials. The polynomial p(x) = C3 x2 + C2 x + C1 is represented in NumPy as : ( C1, C2, C3 ) { the coefficients (constants)}. Let take two polynomials p(x) and q(x) then add these to get r(x) = p(x) + q(x) as
2 min read
numpy.char.add() function in Python
The add() method of the char class in the NumPy module is used for element-wise string concatenation for two arrays of str or unicode. numpy.char.add()Syntax : numpy.char.add(x1, x2)Parameters : x1 : first array to be concatenated (concatenated at the beginning)x2 : second array to be concatenated (concatenated at the end)Returns : Array of strings
2 min read
Add Watermark to PDF using PyPDF4 in Python
We are quite familiar with the most commonly used data format of PDF (Portable Document Format), with an extension .pdf. While the PDF was originally invented by Adobe, though maintained by ISO now, is used to present and exchange documents across various OSs. Installation It could be installed using pip or conda depending on whether you are using
2 min read
Extract and Add FLAC Audio Metadata using the mutagen module in Python
Audio metadata is information embedded into audio files to identify and label audio files. Metadata includes information like artist, genre, album and track number. This information is very essential for making music players and other related applications. Streaming platforms also use metadata to categorize music according to various filters like a
3 min read
How to Add Markers to a Graph Plot in Matplotlib with Python?
In this article, we will learn how to add markers to a Graph Plot in Matplotlib with Python. For that just see some concepts that we will use in our work. Graph Plot: A plot is a graphical technique for representing a data set, usually as a graph showing the relationship between two or more variables.Markers: The markers are shown in graphs with di
2 min read
How to add hours to the current time in Python?
Prerequisites: Datetime module Every minute should be enjoyed and savored. Time is measured by the hours, days, years, and so on. Time helps us to make a good habit of organizing and structuring our daily activities. In this article, we will see how we can extract real-time from a python module. There are various ways to pass the date and time feat
3 min read
Article Tags :
Practice Tags :