How to Combine Two Sets in Python Using a For Loop?

Estimated read time 2 min read

To combine two sets in Python using a for loop, you can iterate over one set and add its elements to the other set. Here’s an example:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
combined_set = set1.copy()  # Create a copy of set1

for item in set2:
    combined_set.add(item)

print(combined_set)

In this example, we start by creating a copy of set1 using the copy() method to preserve its original contents. Then, we iterate over each item in set2 using a for loop. For each item, we use the add() method to add it to the combined_set. The add() method ensures that only unique elements are added to the set.

After the loop finishes, combined_set will contain all the elements from both set1 and set2, excluding any duplicates.

Note that the order of the elements in the resulting set may not necessarily be the same as the order of iteration, as sets do not preserve the original order of elements. If you need to maintain a specific order, you may consider using a different data structure such as a list.

Choose this approach when you specifically need to use a for loop to combine the sets or when you want to perform additional operations within the loop. Otherwise, the more concise method using the union operator (|) or the update() method can be used to combine sets efficiently.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply