.copy()
Published Jun 28, 2024
Contribute to Docs
In Python, the .copy()
method returns a shallow copy of a specified set. The shallow copy is a new set that contains references to the elements in the original set, not the elements themselves. It can be used when it is important to work with the new set without modifying the original set.
Syntax
set.copy()
set
: The set to be copied.
Example
The following example demonstrates the usage of the .copy()
method:
original_set = { 'First', 'Second', 'Third' }print (original_set)new_set = original_set.copy()new_set.add('Fourth')print(new_set)
The above code produces the following output:
{'First', 'Second', 'Third'}{'First', 'Second', 'Third', 'Fourth'}
Note: Unlike lists, a set element has no order or index. Hence, though the elements in the output are shown in order, they can be placed differently in other cases.
Codebyte Example
The following codebyte example demonstrates the usage of the .copy()
method:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours