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 Program to Find All File with .txt Extension Present Inside a Directory
Python Program to Delete an Element From a Dictionary
Java Program to Implement Dijkstra’s Algorithm using Set
Python setattr()
Deep Learning with Python - Francois Cholletf
Python del Statement
Python sleep()
Python Program to Calculate the Area of a Triangle
Python String istitle()
Python List reverse()
Python range()
Python List copy()
Python eval()
Python delattr()
Python Program to Check Armstrong Number
Python __import__()
Python issubclass()
Python Errors and Built-in Exceptions
Python min()
Python callable()
Python Program to Check If a String Is a Number (Float)
Python Deep Learning Cookbook - Indra den Bakker
Deep Learning in Python - LazyProgrammer
Python getattr()
Deep Learning with Python - Francois Chollet
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Program to Iterate Over Dictionaries Using for Loop
Python Program to Generate a Random Number
Python Set clear()
Python Program to Compute all the Permutation of the String
Python Namespace and Scope
Python String rsplit()