Python – Loop Sets

1. What Does “Loop Sets” Mean?

Looping a set means going through each item one by one.

Remember:
👉 Sets are unordered
👉 You will not get items in fixed order

2. Loop Through Set Using for

This is the most common and easiest way.

Example

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

for fruit in fruits:
print(fruit)

Output order may change.

3. Loop and Do Something with Items

Example

numbers = {1, 2, 3, 4}

for n in numbers:
print(n * 2)

4. Loop with Condition

Example

nums = {10, 20, 30, 40}

for n in nums:
if n > 20:
print(n)

5. Loop Using while (Not Recommended)

Sets do not support index, so while is not useful directly.

❌ Wrong

i = 0
while i < len(nums):
print(nums[i])

6. Loop After Converting Set to List

Example

colors = {"red", "blue", "green"}
color_list = list(colors)

for i in range(len(color_list)):
print(color_list[i])

👉 Order is still not guaranteed.

7. Loop with Membership Check

Example

names = {"Amit", "Ravi", "Sita"}

for name in names:
if "a" in name.lower():
print(name)

8. Common Beginner Mistakes

❌ Expecting Fixed Order

print(list(fruits))

Order may change each time.

❌ Trying to Modify Set During Loop

for n in nums:
nums.remove(n)

❌ Error.

✔ Correct:

for n in list(nums):
nums.remove(n)

9. Simple Practice Examples

Example 1: Print All Items

items = {"pen", "book", "eraser"}

for item in items:
print(item)

Example 2: Count Items

count = 0
for _ in items:
count += 1

print(count)

Example 3: Print Even Numbers

nums = {1, 2, 3, 4, 5, 6}

for n in nums:
if n % 2 == 0:
print(n)

10. Summary (Loop Sets)

✔ Use for loop
✔ Sets have no index
✔ Order is not fixed
✔ Convert to list if needed
✔ Useful for unique data

📘 Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • Join Sets

  • Set Methods

  • Set Exercises

  • Dictionaries (easy)

Just tell me 😊

You may also like...