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 Tuple count()
Python Program to Access Index of a List Using for Loop
Python bytes()
Python oct()
Intelligent Projects Using Python - Santanu Pattanayak
Python Program to Check if a Number is Odd or Even
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python String join()
Python help()
Python Program to Check If a List is Empty
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python format()
Python Program to Reverse a Number
Python Set union()
Python eval()
Python pow()
Python Program to Display Calendar
Python Program to Find the Factorial of a Number
Python map()
Python Set remove()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python while Loop
Python Program to Find the Sum of Natural Numbers
Python String isalpha()
Python Program to Get the Class Name of an Instance
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Delete an Element From a Dictionary
Python filter()
Python compile()
Python Program to Check If Two Strings are Anagram
Python String isdigit()
Python Program to Illustrate Different Set Operations