Loops with Sets in Python

Loops with Sets in Python

Introduction to Sets

Sets in Python are an unordered collection of unique elements. They are useful for eliminating duplicates and performing set ope

Characteristics of sets:

  • Uniqueness: No dup
  • Unordered: The
  • Mutable: Set

Creating a Set: 

# Creating a set using curly braces
my_set = {1, 2, 3, 4, 5}
# Creating a set using the set() function
another_set = set([5, 6, 7, 8])

Using for Loops with Sets

You can use for loops to iterate over the elements of a set just like you would with lists or tuples.

Iterating Over a Set:

Here’s how you can use a for loop to iterate over the elements of a set. 

my_set = {10, 20, 30, 40, 50}
for element in my_set:
    print(element)

Explanation:

  • The for loop iterates over each element of my_set.
  • Note that the order of iteration might differ between runs, as sets are unordered.

Practical Example: Calculating the Sum of Set Elements

Let’s calculate the sum of the elements in a set. 

my_set = {1, 2, 3, 4, 5}
# Initialize the sum total_sum = 0 
total_sum = 0
# Iterate over the set and add each element to the sum total_sum
for element in my_set:
     total_sum += element
print("The sum of the elements is:", total_sum)

Nested Loops with Sets

Nested loops can be useful when you need to compare each element of one set with every element of another set, or even within the same set.

Example: Finding Pairs of Elements

Let’s find all possible pairs of elements within a set. 

my_set = {1, 2, 3} 
# Find all possible pairs 
pairs = set() 
for elem1 in my_set: 
   for elem2 in my_set: 
       if elem1 != elem2: 
          pairs.add((elem1, elem2)) 
print("All pairs of elements:", pairs)

 Explanation:

  • We use two nested for loops to compare each element with every other element.
  • The condition if elem1 != elem2 ensures we don’t create pairs of the same element with itself.

Example: Finding Common Elements Between Two Sets

We can compare elements from two sets to find the common elements. 

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Find common elements
common_elements = set()
for elem1 in set1:
    for elem2 in set2:
       if elem1 == elem2:
            common_elements.add(elem1)
print("Common elements:", common_elements)

 Explanation:

  • Two nested for loops compare each element of set1 with each element of set2.
  • Common elements are added to the common_elements set.

Practical Examples

Example: Filtering Odd Elements

Suppose we have a set of integers and want to extract only the odd elements. 

my_set = {10, 15, 20, 25, 30}
# Set for odd elements
odds = set()
# Iterate over the set and add odd elements
for element in my_set:
    if element % 2 != 0:
        odds.add(element)
print("Odd elements:", odds)

Example: Counting Element Occurrences

If you have multiple sets and want to count how many times each element appears across all sets, you can use a loop. 

sets = [{1, 2, 3}, {3, 4, 5}, {5, 6, 7}]
# Dictionary to count occurrences
count = {}
# Iterate over all sets
for s in sets:
    for element in s:
        if element in count:
            count[element] += 1
        else:
            count[element] = 1
print("Occurrences of elements:", count)

Explanation:

  • A dictionary is used to count occurrences of each element across all sets.
  • We iterate through each set and each element to update the count.

Practice Exercise

Exercise: Intersection of Multiple Sets 

# List of multiple sets
sets = [{1, 2, 3, 4}, {3, 4, 5, 6}, {4, 5, 6, 7}]
# Find the intersection of all sets
intersection = sets[0]
for s in sets[1:]:
    intersection &= s
print("Intersection of sets:", intersection)

Write a program to find the intersection of multiple sets. You will need to use loops to iterate through the sets and find the common elements.

Explanation:

  • We initialize the intersection with the first set.

The &= operator is used to update the intersection by finding common elements with each subsequent set.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Facebook
Twitter
LinkedIn
WhatsApp
Email
Print