- Python Basics
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python Control Statements
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Useful Resources
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
- Python - Questions & Answers
- Python - Online Quiz
- Python - Programming Examples
- Python - Quick Guide
- Python - Useful Resources
- Python - Discussion
Python - Add Set Items
Add Set Items
Adding set items implies including new elements into an existing set. In Python, sets are mutable, which means you can modify them after they have been created. While the elements within a set must be immutable (such as integers, strings, or tuples), the set itself can be modified.
You can add items to a set using various methods, such as add(), update(), or set operations like union (|) and set comprehension.
One of the defining features of sets is their ability to hold only immutable (hashable) objects. This is because sets internally use a hash table for fast membership testing. Immutable objects are hashable, meaning they have a hash value that never changes during their lifetime.
Add Set Items Using the add() Method
The add() method in Python is used to add a single element to the set. It modifies the set by inserting the specified element if it is not already present. If the element is already in the set, the add() method has no change in the set.
Syntax
Following is the syntax to add an element to a set −
set.add(obj)
Where, obj is an object of any immutable type.
Example
In the following example, we are initializing an empty set called "language" and adding elements to it using the add() method −
# Defining an empty set language = set() # Adding elements to the set using add() method language.add("C") language.add("C++") language.add("Java") language.add("Python") # Printing the updated set print("Updated Set:", language)
It will produce the following output −
Updated Set: {'Python', 'Java', 'C++', 'C'}
Add Set Items Using the update() Method
In Python, the update() method of set class is used to add multiple elements to the set. It modifies the set by adding elements from an iterable (such as another set, list, tuple, or string) to the current set. The elements in the iterable are inserted into the set if they are not already present.
Syntax
Following is the syntax to update an element to a set −
set.update(obj)
Where, obj is a set or a sequence object (list, tuple, string).
Example: Adding a Single Set Item
In the example below, we initialize a set called "my_set". Then, we use the update() method to add the element "4" to the set −
# Define a set my_set = {1, 2, 3} # Adding element to the set my_set.update([4]) # Print the updated set print("Updated Set:", my_set)
Following is the output of the above code −
Updated Set: {1, 2, 3, 4}
Example: Adding any Sequence Object as Set Items
The update() method also accepts any sequence object as argument.
In this example, we first define a set and a tuple, lang1 and lang2, containing different programming languages. Then, we add all elements from "lang2" to "lang1" using the update() method −
# Defining a set lang1 = {"C", "C++", "Java", "Python"} # Defining a tuple lang2 = {"PHP", "C#", "Perl"} lang1.update(lang2) print (lang1)
The result obtained is as shown below −
{'Python', 'C++', 'C#', 'C', 'Java', 'PHP', 'Perl'}
Example
In this example, a set is constructed from a string, and another string is used as argument for update() method −
set1 = set("Hello") set1.update("World") print (set1)
It will produce the following output −
{'H', 'r', 'o', 'd', 'W', 'l', 'e'}
Add Set Items Using Union Operator
In Python, the union operator (|) is used to perform a union operation between two sets. The union of two sets contains all the distinct elements present in either of the sets, without any duplicates.
We can add set items using the union operator by performing the union operation between two sets using the "|" operator or union() function, which combines the elements from both sets into a new set, containing all unique elements present in either of the original sets.
Example
The following example combine sets using the union() method and the | operator to create new sets containing unique elements from the original sets −
# Defining three sets lang1 = {"C", "C++", "Java", "Python"} lang2 = {"PHP", "C#", "Perl"} lang3 = {"SQL", "C#"} # Performing union operation combined_set1 = lang1.union(lang2) combined_set2 = lang2 | lang3 # Print the combined set print ("Combined Set1:", combined_set1) print("Combined Set2:", combined_set2)
Output of the above code is as shown below −
Combined Set1: {'C#', 'Perl', 'C++', 'Java', 'PHP', 'Python', 'C'} Combined Set2: {'C#', 'Perl', 'PHP', 'SQL'}
Example
If a sequence object is given as argument to union() method, Python automatically converts it to a set first and then performs union −
lang1 = {"C", "C++", "Java", "Python"} lang2 = ["PHP", "C#", "Perl"] lang3 = lang1.union(lang2) print (lang3)
The output produced is as follows −
{'PHP', 'C#', 'Python', 'C', 'Java', 'C++', 'Perl'}
Add Set Items Using Set Comprehension
In Python, set comprehension is a way to create sets using a single line of code. It allows you to generate a new set by applying an expression to each item in an iterable (such as a list, tuple, or range), optionally including a condition to filter elements.
We can add set items using set comprehension by iterating over an iterable, applying an expression to each element, and enclosing the comprehension expression within curly braces {} to generate a new set containing the results of the expression applied to each element.
Example
In the following example, we are defining a list of integers and then using set comprehension to generate a set containing the squares of those integers −
# Defining a list containing integers numbers = [1, 2, 3, 4, 5] # Creating a set containing squares of numbers using set comprehension squares_set = {num ** 2 for num in numbers} # Printing the set containing squares of numbers print("Squares Set:", squares_set)
Following is the output of the above code −
Squares Set: {1, 4, 9, 16, 25}