Post

Python Set copy() Method

In this tutorial, we will understand about the python set copy() method and its uses.

Python Set copy() Method

The Python set copy() method returns a shallow copy of a set. A shallow copy means the new set contains references to the same objects as the original set. However, the set itself is a new object, allowing you to modify one set without affecting the other.

The syntax of the copy() method is:

1
set.copy()

Python set copy() Parameters

The copy() method doesn’t take any parameters. It simply creates and returns a new set containing the same elements as the original set.

Understanding shallow copy is important when working with sets containing mutable objects. Let’s see some examples:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Example 1: Basic set copy
original = {1, 2, 3}
copied = original.copy()
original.add(4)
print(original)  # Output: {1, 2, 3, 4}
print(copied)    # Output: {1, 2, 3}

# Example 2: Copying sets with tuples
numbers = {(1, 2), (3, 4)}
numbers_copy = numbers.copy()
print(numbers_copy)  # Output: {(1, 2), (3, 4)}

# Example 3: Shallow copy behavior
nested = {1, 2, (3, [4, 5])}
nested_copy = nested.copy()
# Modifying the nested list affects both sets
list(nested)[2][1][0] = 6
print(nested)      # Output: {1, 2, (3, [6, 5])}
print(nested_copy) # Output: {1, 2, (3, [6, 5])}

For deep copying of sets containing nested objects, use the copy.deepcopy() function from Python’s copy module.

This post is licensed under CC BY 4.0 by the author.