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:
Python List Comprehension
Python Set pop()
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python String rsplit()
Python Errors and Built-in Exceptions
Python help()
Python oct()
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python setattr()
Python dir()
Python Program to Generate a Random Number
Python *args and **kwargs
Python String startswith()
Python Object Oriented Programming
Python classmethod()
Python String expandtabs()
Python open()
Python Iterators
Python List append()
Python String translate()
Python Program to Convert Two Lists Into a Dictionary
Deep Learning with Python - Francois Chollet
Python Program to Count the Number of Occurrence of a Character in String
Python Program to Return Multiple Values From a Function
Python Set intersection()
Python Program to Iterate Through Two Lists in Parallel
Python strptime()
Python String isdigit()
Intelligent Projects Using Python - Santanu Pattanayak
Python String zfill()
Python if...else Statement
Python __import__()