Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python - Loop Sets – Complete Guide for Beginners

A Set in Python is a collection used to store multiple unique values. Sets are unordered, mutable, and do not allow duplicate items.

One of the most common operations when working with sets is looping through the items. Since sets are collections, Python provides powerful looping mechanisms to access and process every element efficiently.

In this tutorial, you will learn:

  • How to loop through a set
  • Using for loops with sets
  • Looping with enumerate()
  • Nested loops with sets
  • Filtering items while looping
  • Real-world examples
  • Common mistakes and best practices

By the end of this guide, you'll understand how to work with set data using loops effectively.


Why Loop Through a Set?

Looping allows you to:

  • Access every item in a set
  • Display values
  • Filter data
  • Perform calculations
  • Search for specific items
  • Process large collections efficiently

Example:

fruits = {
    "apple",
    "banana",
    "orange"
}

for fruit in fruits:
    print(fruit)

Output:

apple
banana
orange

The order may vary because sets are unordered.


Basic Loop Through a Set

The simplest way to loop through a set is using a for loop.

Syntax

for item in myset:
    print(item)

Example

colors = {
    "red",
    "green",
    "blue"
}

for color in colors:
    print(color)

Output:

red
green
blue

Understanding Unordered Output

Unlike lists, sets do not maintain insertion order.

Example:

numbers = {
    1,
    2,
    3,
    4
}

for num in numbers:
    print(num)

Possible Output:

3
1
4
2

The order may be different every time.


Loop Through String Values

languages = {
    "Python",
    "Java",
    "C++"
}

for language in languages:
    print(language)

Output:

Python
Java
C++

Loop Through Numeric Values

scores = {
    75,
    80,
    90,
    95
}

for score in scores:
    print(score)

Output:

75
80
90
95

Order is not guaranteed.


Using enumerate() with Sets

Although sets do not have indexes, you can generate temporary index numbers using enumerate().

fruits = {
    "apple",
    "banana",
    "orange"
}

for index, fruit in enumerate(fruits):
    print(index, fruit)

Possible Output:

0 apple
1 banana
2 orange

Note

These are generated positions, not actual set indexes.


Loop and Check Conditions

You can filter values while looping.

numbers = {
    1, 2, 3, 4, 5,
    6, 7, 8, 9, 10
}

for num in numbers:
    if num % 2 == 0:
        print(num)

Output:

2
4
6
8
10

Only even numbers are displayed.


Using break in Set Loops

The break statement stops the loop immediately.

fruits = {
    "apple",
    "banana",
    "orange"
}

for fruit in fruits:
    print(fruit)
    break

Output:

apple

The actual item may vary.


Using continue in Set Loops

The continue statement skips the current iteration.

numbers = {
    1, 2, 3, 4, 5
}

for num in numbers:
    if num == 3:
        continue

    print(num)

Output:

1
2
4
5

Nested Loops with Sets

You can use loops inside loops.

letters = {
    "A",
    "B"
}

numbers = {
    1,
    2
}

for letter in letters:
    for number in numbers:
        print(letter, number)

Output:

A 1
A 2
B 1
B 2

Loop Through a Set of Mixed Data Types

data = {
    "Python",
    100,
    True,
    3.14
}

for item in data:
    print(item)

Output:

Python
100
True
3.14

Count Items While Looping

fruits = {
    "apple",
    "banana",
    "orange"
}

count = 0

for fruit in fruits:
    count += 1

print(count)

Output:

3

Calculate Total from a Numeric Set

numbers = {
    10,
    20,
    30,
    40
}

total = 0

for num in numbers:
    total += num

print(total)

Output:

100

Create a New Set While Looping

numbers = {
    1, 2, 3, 4, 5
}

squares = set()

for num in numbers:
    squares.add(num ** 2)

print(squares)

Output:

{1, 4, 9, 16, 25}

Using Set Comprehension

Python provides a shorter way to loop through sets.

numbers = {
    1, 2, 3, 4, 5
}

squares = {
    x ** 2
    for x in numbers
}

print(squares)

Output:

{1, 4, 9, 16, 25}

Real-World Example: User Access Control

permissions = {
    "read",
    "write",
    "delete"
}

for permission in permissions:
    print(
        "Allowed:",
        permission
    )

Output:

Allowed: read
Allowed: write
Allowed: delete

Real-World Example: Email Processing

emails = {
    "user1@gmail.com",
    "user2@gmail.com",
    "user3@gmail.com"
}

for email in emails:
    print(
        "Sending to:",
        email
    )

Output:

Sending to: user1@gmail.com
Sending to: user2@gmail.com
Sending to: user3@gmail.com

Common Mistakes

Mistake 1: Using Indexes

Incorrect:

fruits = {
    "apple",
    "banana"
}

print(fruits[0])

Output:

TypeError

Sets do not support indexing.


Mistake 2: Assuming Order

Incorrect:

for fruit in fruits:
    print(fruit)

Do not assume items appear in a specific order.


Mistake 3: Modifying a Set During Iteration

Incorrect:

for item in fruits:
    fruits.remove(item)

Output:

RuntimeError

Correct:

for item in fruits.copy():
    fruits.remove(item)

Best Practices

Use for Loops

for item in myset:
    print(item)

Use Set Comprehensions

newset = {
    x * 2
    for x in myset
}

Avoid Depending on Order

Sets are unordered collections.

Use Membership Testing

if "apple" in fruits:
    print("Found")

Quick Summary

TaskMethod
Loop through setfor loop
Generate positionsenumerate()
Stop loopbreak
Skip iterationcontinue
Filter valuesif statement
Create new setadd()
Shorter loop syntaxset comprehension

Conclusion

Looping through sets is one of the most important skills when working with Python collections. Because sets are unordered and contain unique values, they are ideal for filtering data, processing records, and performing membership tests.

By mastering for loops, enumerate(), break, continue, nested loops, and set comprehensions, you can efficiently work with set data in real-world Python applications.

Understanding how to loop through sets correctly will help you write cleaner, faster, and more professional Python code. 




Post a Comment

0 Comments