Table of Contents
The copy() method returns a shallow copy of the set.
A set can be copied using = operator in Python. For example:
numbers = {1, 2, 3, 4}
new_numbers = numbers
The problem with copying the set in this way is that if you modify the numbers set, the new_numbers set is also modified.
numbers = {1, 2, 3, 4}
new_numbers = numbers
new_numbers.add(5)
print('numbers: ', numbers)
print('new_numbers: ', new_numbers)
Output
numbers: {1, 2, 3, 4, 5}
new_numbers: {1, 2, 3, 4, 5}
However, if you need the original set to be unchanged when the new set is modified, you can use the copy() method.
The syntax of copy() is:
set.copy()
1. copy() Parameters
It doesn’t take any parameters.
2. Return Value from copy()
The copy() method returns a shallow copy of the set.
3. Example 1: How the copy() method works for sets?
numbers = {1, 2, 3, 4}
new_numbers = numbers.copy()
new_numbers.add(5)
print('numbers: ', numbers)
print('new_numbers: ', new_numbers)
Output
numbers: {1, 2, 3, 4}
new_numbers: {1, 2, 3, 4, 5}
Related posts:
How to get current date and time in Python?
Python Program to Find the Square Root
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Global, Local and Nonlocal variables
Python strptime()
Python Program to Merge Two Dictionaries
Python Program to Calculate the Area of a Triangle
Python Namespace and Scope
Python Tuple count()
Python List insert()
Python enumerate()
Python bool()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Tuple
Python Program to Get a Substring of a String
Python String isalnum()
Python Program to Generate a Random Number
Python @property decorator
Python Program to Differentiate Between type() and isinstance()
APIs in Node.js vs Python - A Comparison
Python Program to Sort a Dictionary by Value
Python Program to Find the Factorial of a Number
Convert a Map to an Array, List or Set in Java
Python pass statement
Python Set issubset()
Python if...else Statement
Python Dictionary update()
Python Program to Print the Fibonacci sequence
Python __import__()
Python Dictionary pop()
Python List Comprehension
Python Program to Find the Factors of a Number