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

Python Set | update()

Last Updated : 01 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python update() function in set adds elements from a set (passed as an argument) to the set. If the element is present in both of the sets then the element comes only one time in the updated set.

Python Set update() Method Syntax

Syntax :  set1.update(set2) 

Here set1 is the set in which set2 will be added.

Parameters : Update() method takes any number of argument. The arguments can be a set, list, tuples or a dictionary. It automatically converts into a set and adds to the set. 

Return value : This method adds set2 to set1 and returns nothing. 

Set update() Method Example

Working with Python set update List

In this example there are three list initially. The first and second list is converted to the set using the set() function. The update() method is then used to merge the elements of ‘set2' into ‘set1', resulting in a combined set. The code prints this updated set. Next, the update() method is applied again to include the elements from a third list, ‘list3', into the already updated ‘set1'. Finally, the code prints the final merged set, which contains elements from ‘set2', ‘list3' , and the original ‘set1'.

Python3




list1 = [1, 2, 3]
list2 = [5, 6, 7]
list3 = [10, 11, 12]
set1 = set(list2)
set2 = set(list1)
set1.update(set2)
print(set1)
set1.update(list3)
print(set1)


Output : 

{1, 2, 3, 5, 6, 7}
{1, 2, 3, 5, 6, 7, 10, 11, 12}

Python Set update Element in Set

This Python program explains the update() method for sets. Initially, two lists, ‘list1' and ‘list2', containing integers, are converted into sets, ‘set1' and ‘set2'. The update() method is then used to merge the unique elements of ‘set2' into ‘set1', creating a consolidated set. This set is printed to display the combined elements. Furthermore, the update() method is applied to include the elements from the ‘alphabet_set', expanding the set to encompass characters ‘a’, ‘b’, and ‘c’. The final updated ‘set1' is printed again, now elements from both ‘set2' and ‘alphabet_set'.

Python3




list1 = [1, 2, 3, 4]
list2 = [1, 4, 2, 3, 5]
alphabet_set = {'a', 'b', 'c'}
set1 = set(list2)
set2 = set(list1)
set1.update(set2)
print(set1)
set1.update(alphabet_set)
print(set1)


Output : 

{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 'c', 'b', 'a'}

Add Elements of the Dictionary to Set

This Python code updates a set named number with elements from a dictionary called ‘num_Dict'. Initially, number contains integers from 1 to 5, while ‘num_Dict' stores integer-to-string mappings for numbers 6 to 10. The update() method merges the keys from ‘num_Dict' into the ‘number' set, resulting in a set containing unique elements from both the original set and the dictionary. The output displays the updated set, which now includes integers from 1 to 10, combining numeric and textual representations.

Python3




number = {1, 2, 3, 4, 5}
num_Dict = {6: 'Six', 7: 'Seven', 8: 'Eight',
            9: 'Nine', 10: 'Ten'}
number.update(num_Dict)
print("Updated set: ", number)


Output:

Updated set:  {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}


Previous Article
Next Article

Similar Reads

Set update() in Python to do union of n arrays
We are given n arrays of any size which may have common elements, we need to combine all these arrays in such a way that each element should occurs only once and elements should be in sorted order? Examples: Input : arr = [[1, 2, 2, 4, 3, 6], [5, 1, 3, 4], [9, 5, 7, 1], [2, 4, 1, 3]] Output : [1, 2, 3, 4, 5, 6, 7, 9] A simple solution for this prob
2 min read
MongoDB Python | Insert and Update Data
Prerequisites : MongoDB Python Basics We would first understand how to insert a document/entry in a collection of a database. Then we would work on how to update an existing document in MongoDB using pymongo library in python. The update commands helps us to update the query data inserted already in MongoDB database collection. Insert data We would
3 min read
Python SQLite - Update Data
In this article, we will discuss how we can update data in tables in the SQLite database using Python - sqlite3 module. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement. Syntax: UPDATE table_name SET col
7 min read
Python | Pandas Series.update()
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. Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object suppo
2 min read
Update column value of CSV in Python
Prerequisites: Pandas In this article, we will discuss ways in which the value(s) of a column can be updated. The best and the optimal way to update any column value of a CSV is to use the Pandas Library and the DataFrame functions. Link for the CSV file in use - Click here Method 1 Approach Import moduleOpen CSV file and read its dataFind column t
3 min read
Python: Update Nested Dictionary
A Dictionary in Python works similar to the Dictionary in the real world. Keys of a Dictionary must be unique and of immutable data types such as Strings, Integers, and tuples, but the key-values can be repeated and be of any type. Refer to the below article to get the idea about dictionaries: Python Dictionary Nested Dictionary: The nested diction
6 min read
Python MySQL - Update Query
A connector is employed when we have to use MySQL with other programming languages. The work of MySQL-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. Update Clause The update is used to change the existing values in a database. By using u
2 min read
Matplotlib.axes.Axes.update() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. matplotlib.axes.Axes.update() Function The Axes.up
2 min read
Matplotlib.artist.Artist.update() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Artist class contains Abstract base class for objects that render into a FigureCanvas. All visible elements in a figure are subclasses of Artist. matplotlib.artist.Artist.update() method The update() method in artist module of matplotlib library is
2 min read
How to update data in a Collection using Python?
MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability. Updating Data in MongoDB We can update data in a collection using update_one() method and update_many() method. update_one() update_one() method update first occurrence i
2 min read
How to get COVID 19 update using Covid module in Python?
A new Python library which tells the COVID-19 related information (country-wise) and it show that how many cases of confirmed, active, deaths, recovered found in that particular Country. Requirement: You have python package named COVID and python >= 3.6 Installation: pip install covid Dependencies: pydantic requests Example: from covid import Co
3 min read
Matplotlib.axis.Axis.update() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. Matplotlib.axis.Axis.update() Function The Axis.update() function in axis module of matplotlib library is used to update this art
2 min read
Matplotlib.axis.Tick.update() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. Matplotlib.axis.Tick.update() Function The Tick.update() function in axis module of matplotlib library is used to update this art
2 min read
Python SQLite - Update Specific Column
In this article, we will discuss how to update a specific column of a table in SQLite using Python. In order to update a particular column in a table in SQL, we use the UPDATE query. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE stat
3 min read
Python MariaDB - Update Query using PyMySQL
MariaDB is an open-source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python. In this article, we will look into the process of using the UPDATE query on a table of the database using pymysql. The update is used to change the existing values in a dat
2 min read
How to update a pickle file in Python?
Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on a disk. What pickle does is that it “serializes” the object first before writing it to file. Pickling is a way to convert a python object (list, dict, etc.) into a character stream. The idea is th
3 min read
PostgreSQL Python - Update Data in Table
In this article, we are going to see how to update existing data in PostgreSQL tables using the pyscopg2 module in Python. In PostgreSQL, the UPDATE TABLE with where clause is used to update the data in the existing table from the database. Syntax: UPDATE <table_name> SET column1 = value1, column2 = value2,..... WHERE [condition] To execute a
2 min read
How to Update all the Values of a Specific Column of SQLite Table using Python ?
In this article, we are going to update all the values of a specific column of a given SQLite table using Python. In order to update all the columns of a particular table in SQL, we use the UPDATE query. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple colu
3 min read
Python PostgreSQL - Update Table
In this article, we will see how to Update data in PostgreSQL using python and Psycopg2. The update command is used to modify the existing record in the table. By default whole records of the specific attribute are modified, but to modify some particular row, we need to use the where clause along with the update clause. Syntax for Update Clause UPD
2 min read
Update multiple rows in same query in PostgreSQL using Pyscopg2-Python
In this article, we are going to update multiple rows in the same query in PostgreSQL using Pyscopg2in Python. We can update multiple values at once by using the update clause from PostgreSQL. First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2.connect() method. Syntax of update clause:UPDATE
1 min read
Python SQLAlchemy - Update table structure
In this article, we are going to update the structure of the table using the sqlalchemy module. The structure of the table includes name of columns, the datatype of columns, constraints, keys, etc which we are going to update in this post. Installing the requirements: Let us first install the SQLAlchemy module by running the following pip command i
3 min read
Dynamically Update Multiple Rows with PostgreSQL and Python
In this tutorial, we will explore how to dynamically update multiple rows in a PostgreSQL database using Python. By the end of this tutorial, you'll have a solid understanding of how to write efficient Python code that interacts with PostgreSQL to update multiple rows in a database. We'll cover topics such as connecting to a PostgreSQL database, ex
3 min read
Update JSON Key Name in Python
Working with JSON data is a common task in Python, and there are various scenarios where you might need to update the key names within a JSON object. In this article, we will explore five different simple and generally used methods to achieve this task, accompanied by code examples. How to Update Json Key Name in Python?Below, are the ways To Updat
3 min read
How to update existing table rows in SQLAlchemy in Python?
In this article, we are going to see how to use the UPDATE statement in SQLAlchemy against a PostgreSQL database in Python. Creating table for demonstration:Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() function as shown below, create a table called books with columns
2 min read
Python Counter.update() Method
Python's Counter is a subclass of the dict class and provides a convenient way to keep track of the frequency of elements in an iterable. The Counter.update() method is particularly useful for updating the counts of elements in a Counter object based on another iterable or another Counter object. In this article, we will understand about the Counte
2 min read
How to Fix "ValueError: dictionary update sequence element #0 has length X; 2 is required" in Python
The "ValueError: dictionary update sequence element #0 has length X; 2 is required" error typically occurs when trying to update a dictionary with a sequence that does not contain exactly two elements for each key-value pair. This article explains the causes of this error and provides the solutions to fix it. Understanding the ErrorThe "ValueError:
3 min read
Latest Update on Python 4.0
Python remains one of the most popular programming languages in 2024, known for its simplicity, versatility, and extensive ecosystem. As Python continues to evolve with regular updates to the Python 3.x series, speculation about the potential release of Python 4.0 has surfaced. However, recent statements from Guido van Rossum, the creator of Python
6 min read
How to update Python on Windows?
In this article, we are going to see how to update Python in the Windows system. For the sake of example, we will be upgrading from Python 3.6.8 to Python 3.9.6. Here, we will see how to upgrade the Python version. Upgrading Python on WindowsTo check the current version of Python on your system, use the following command in the command prompt: pyth
4 min read
Python Dictionary update() method
Python Dictionary update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs. Example: Original dictionary : {'A': 'Geeks', 'B': 'For'}Updated dictionary : {'A': 'Geeks', 'B': 'Geeks'}Original dictionary : {'A': 'Geeks', 'B': 'For'}Updated dictionary : {'A': 'Geeks', 'B': 'For', 'C
5 min read
Update Jupyter Notebook to the Latest Python Version
To take advantage of the latest features and improvements in Python, it is important to keep your Jupyter Notebook updated with the latest Python version. This article will guide you through the process of updating Jupyter Notebook to the latest Python version. Note: Let's say if we want to Download Install from Python 3.7 to 3.11: Checking the Cur
3 min read
Article Tags :
Practice Tags :