Table of Contents
ToggleCopying sets in Python refers to creating a new set that contains the same elements as an existing set. Unlike simple variable assignment, which creates a reference to the original set, copying ensures that changes made to the copied set do not affect the original set, and vice versa.
There are different methods for copying a set in Python, including using the copy() method, the set() function, or set comprehension.
The copy() method in the set class is used to create a shallow copy of a set object.
A shallow copy means that the method creates a new collection object, but does not create copies of the objects contained within the original collection. Instead, it copies the references to these objects.
set.copy()
The copy() method returns a new set which is a shallow copy of the existing set.
lang1 = {"C", "C++", "Java", "Python"}
print("lang1:", lang1, "id(lang1):", id(lang1))
lang2 = lang1.copy()
print("lang2:", lang2, "id(lang2):", id(lang2))
lang1.add("PHP")
print("After updating lang1")
print("lang1:", lang1, "id(lang1):", id(lang1))
print("lang2:", lang2, "id(lang2):", id(lang2))
lang1: {'Python', 'Java', 'C', 'C++'} id(lang1): 2451578196864
lang2: {'Python', 'Java', 'C', 'C++'} id(lang2): 2451578197312
After updating lang1
lang1: {'Python', 'C', 'C++', 'PHP', 'Java'} id(lang1): 2451578196864
lang2: {'Python', 'Java', 'C', 'C++'} id(lang2): 2451578197312
The Python set() function is used to create a new set object. It takes an iterable as an argument and converts it into a set, removing any duplicate elements in the process.
# Original set
original_set = {1, 2, 3, 4}
# Copying the set using the set() function
copied_set = set(original_set)
print("Copied set:", copied_set)
# Demonstrating that the sets are independent
copied_set.add(5)
print("Copied set:", copied_set)
print("Original set:", original_set)
Copied set: {1, 2, 3, 4}
Copied set: {1, 2, 3, 4, 5}
Original set: {1, 2, 3, 4}
Set comprehension is a concise way to create sets in Python. It is used to generate a new set by iterating over an iterable and optionally applying conditions to filter elements.
# Original set
original_set = {1, 2, 3, 4, 5}
# Copying the set using set comprehension
copied_set = {x for x in original_set}
print("Copied set:", copied_set)
Copied set: {1, 2, 3, 4, 5}
