Python Set - copy method

Top copy a set object just invoke copy method exposed by the object and you get a shallow copy of the original set

Set Updated 16 Sep 2016 1 min read

Method signature

copy()

Method overview

The copy() method returns a copy of the set. The copy returned contains shallow copy of the elements.
i.e., A new set object is created and the elements are copied from the source set.
The elements are not created afresh.They are just referred.

Return Value

A new set object containing shallow copy of the elements from the original set.

Example

python
# Example Python program that copies the elements of

            # a set into another new set

# Create a set of jobs for printing

            printJobs = {"Job1", "Job2", "Job3", "Job4", "Job5"}

# Copy the jobs into a backup set

            backupJobs  = printJobs.copy()

print("Newly created set using copy():")

            print(backupJobs)

print("Ids of the sets:")

            print(id(printJobs))

            print(id(backupJobs))

# While the backup set is newly created the elements are not

            print("Ids of first elements from both the sets:")

            elem = next(iter(printJobs))

            print(id(elem))

elem = next(iter(backupJobs))

            print(id(elem))

Output

Output
Newly created set using copy():

{'Job2', 'Job5', 'Job1', 'Job3', 'Job4'}

Ids of the sets:

4308111584

4308110240

Ids of first elements from both the sets:

4308014000

4308014000