How do I copy sets in Python with examples?

In Python, you can copy sets using several methods, including the `copy()` method, the `set()` constructor, and the `copy` module. Each method provides a way to create a new set that is a duplicate of an existing set.

Methods to Copy Sets

1. Using the copy() Method

The `copy()` method returns a shallow copy of the set.

2. Using the set() Constructor

You can also create a new set by passing the original set into the `set()` constructor.

3. Using the copy Module

The `copy` module provides a `copy()` function which can be used to create a shallow copy of the set.

Examples

# Original set original_set = {1, 2, 3, 4, 5} # Using the copy() method copied_set1 = original_set.copy() print(copied_set1) # Output: {1, 2, 3, 4, 5} # Using the set() constructor copied_set2 = set(original_set) print(copied_set2) # Output: {1, 2, 3, 4, 5} # Using the copy module import copy copied_set3 = copy.copy(original_set) print(copied_set3) # Output: {1, 2, 3, 4, 5}

Python Set Copy Set Python Sets Set Methods