Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python Set: Iteration (Looping)

Python Set Iteration - Complete Guide

Learn how to iterate over Python sets using for loops, comprehensions, and advanced techniques.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Introduction to Set Iteration
  • For Loop Iteration
  • Sorted Iteration
  • While Loop Iteration
  • Set Comprehension
  • Advanced Iteration Techniques
  • Common Mistakes
  • Interactive Editor
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You Will Learn
  • For loop iteration — the standard way to iterate
  • Sorted iteration — iterating in a specific order
  • While loop iteration — manual control
  • Set comprehension — concise iteration with transformation
  • Advanced techniques — any(), all(), map(), filter()
  • Common mistakes — and how to avoid them

Introduction to Set Iteration

Iteration is the process of accessing each element in a collection sequentially. In Python, sets are iterable objects, meaning you can loop through their elements. However, since sets are unordered, the iteration order is not guaranteed and may vary between runs.

The key characteristics of set iteration are:

  • Unordered — elements are not accessed in a predictable order
  • No indexing — cannot use range(len()) or index-based access
  • Fast — sets are optimized for iteration
  • Cannot modify — modifying a set during iteration raises RuntimeError

💡 Key concept: Since sets are unordered, use sorted() when you need to iterate in a specific order.

For Loop Iteration

1

Standard Iteration

The for loop is the most common way to iterate over a set. It automatically retrieves each element sequentially.

# Basic for loop over a set
fruits = {"apple", "banana", "cherry", "mango", "orange"}
for fruit in fruits:
    print(f"Fruit: {fruit}")

# Output (order may vary):
# Fruit: cherry
# Fruit: apple
# Fruit: mango
# Fruit: banana
# Fruit: orange

# Performing operations during iteration
numbers = {1, 2, 3, 4, 5}
squared = []
for num in numbers:
    squared.append(num ** 2)
print(squared)  # [1, 4, 9, 16, 25] (order may vary)

# Iterating and transforming
words = {"hello", "world", "python"}
upper_words = []
for word in words:
    upper_words.append(word.upper())
print(upper_words)  # ['HELLO', 'WORLD', 'PYTHON'] (order may vary)

Characteristics:

  • No index management required
  • Works with any iterable
  • Order is not guaranteed
  • Cannot modify the set during iteration

Quick Check: Is the iteration order of a set guaranteed? (Answer: No — sets are unordered)

Sorted Iteration

2

Iterating in a Specific Order

The sorted() function returns a sorted list of elements, allowing you to iterate in a predictable order.

# Basic sorted iteration
fruits = {"apple", "banana", "cherry", "mango", "orange"}
for fruit in sorted(fruits):
    print(f"Fruit: {fruit}")

# Output (alphabetical):
# Fruit: apple
# Fruit: banana
# Fruit: cherry
# Fruit: mango
# Fruit: orange

# Sorted with numbers
numbers = {3, 1, 4, 1, 5, 9, 2}
for num in sorted(numbers):
    print(num)  # 1, 2, 3, 4, 5, 9

# Reverse order
for fruit in sorted(fruits, reverse=True):
    print(fruit)  # orange, mango, cherry, banana, apple

# Sorted by length (using key parameter)
words = {"apple", "banana", "cherry", "date"}
for word in sorted(words, key=len):
    print(word)  # date, apple, banana, cherry

# Converting sorted result back to set (order not preserved)
sorted_set = set(sorted(fruits))
print(sorted_set)  # Order is lost

Characteristics:

  • sorted() returns a list, not a set
  • Original set remains unchanged
  • Supports reverse and key parameters
  • Useful for predictable iteration order

Quick Check: What does sorted() return when used on a set? (Answer: A list)

While Loop Iteration

3

Manual Iteration Control

Since sets are unindexed, while loops are not commonly used for set iteration. However, you can use a while loop with an iterator or by converting to a list.

# Using an iterator
fruits = {"apple", "banana", "cherry", "mango"}
iterator = iter(fruits)

while True:
    try:
        fruit = next(iterator)
        print(fruit)
    except StopIteration:
        break

# Converting to list for index-based iteration
fruits = {"apple", "banana", "cherry", "mango"}
fruits_list = list(fruits)
i = 0
while i < len(fruits_list):
    print(f"Index {i}: {fruits_list[i]}")
    i += 1

# Using pop() in a while loop (removes all elements)
numbers = {1, 2, 3, 4, 5}
while numbers:
    element = numbers.pop()
    print(f"Removed: {element}")

print(f"Empty set: {numbers}")

Use cases:

  • When you need manual iterator control
  • When processing all elements with pop()
  • Generally less common than for loops

Quick Check: Can you use index-based iteration on a set? (Answer: No — sets are unindexed)

Set Comprehension

4

Creating New Sets via Iteration

Set comprehension is a concise way to create a new set by iterating over an existing set and applying transformations or filters.

# Basic set comprehension
numbers = {1, 2, 3, 4, 5}
squares = {num ** 2 for num in numbers}
print(squares)  # {1, 4, 9, 16, 25}

# With filtering (only even numbers)
even_squares = {num ** 2 for num in numbers if num % 2 == 0}
print(even_squares)  # {4, 16}

# With strings
words = {"apple", "banana", "cherry", "date"}
upper_words = {word.upper() for word in words if len(word) > 4}
print(upper_words)  # {'APPLE', 'BANANA', 'CHERRY'} (order may vary)

# Nested comprehension
set1 = {1, 2, 3}
set2 = {4, 5, 6}
combined = {x + y for x in set1 for y in set2}
print(combined)  # {5, 6, 7, 8, 9} (order may vary)

# Conditional transformation
numbers = {1, 2, 3, 4, 5}
processed = {num ** 2 if num % 2 == 0 else num for num in numbers}
print(processed)  # {1, 4, 3, 16, 5} (order may vary)

Characteristics:

  • Syntax: {expression for item in set if condition}
  • Returns a new set
  • Original set remains unchanged
  • More concise than traditional loops

Quick Check: What does set comprehension return? (Answer: A new set)

Advanced Iteration Techniques

5

Specialized Iteration Patterns

Python provides several built-in functions for common iteration patterns with sets.

# any() — check if any element satisfies a condition
numbers = {1, 2, 3, 4, 5}
print(any(x > 4 for x in numbers))  # True (5 > 4)
print(any(x > 5 for x in numbers))  # False

# all() — check if all elements satisfy a condition
print(all(x > 0 for x in numbers))  # True
print(all(x > 2 for x in numbers))  # False (1 and 2 are not > 2)

# filter() — create an iterator of elements that satisfy a condition
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
even_numbers = set(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # {2, 4, 6, 8, 10}

# map() — apply a function to all elements
numbers = {1, 2, 3, 4, 5}
squared = set(map(lambda x: x ** 2, numbers))
print(squared)  # {1, 4, 9, 16, 25}

# Iterating with conditions
fruits = {"apple", "banana", "cherry", "mango"}
# Using a generator expression
long_fruits = {fruit for fruit in fruits if len(fruit) > 5}
print(long_fruits)  # {'banana', 'cherry'} (order may vary)

# Using break and continue in set iteration
numbers = {1, 2, 3, 4, 5, 6}
print("Break example:")
for num in numbers:
    if num > 4:
        break
    print(num)  # 1, 2, 3, 4 (order may vary)

print("Continue example:")
for num in numbers:
    if num % 2 == 0:
        continue
    print(num)  # 1, 3, 5 (order may vary)

Functions overview:

  • any() — True if at least one element satisfies the condition
  • all() — True if all elements satisfy the condition
  • filter() — creates an iterator of elements that satisfy a condition
  • map() — applies a function to all elements
  • break — exits the loop early
  • continue — skips to the next iteration

Quick Check: What does any() return if at least one element is truthy? (Answer: True)

Common Mistakes

6

Watch Out For These!

Mistake 1: Modifying a Set During Iteration

# WRONG — raises RuntimeError
numbers = {1, 2, 3, 4, 5}
# for num in numbers:
#     if num % 2 == 0:
#         numbers.remove(num)  # RuntimeError: Set changed size during iteration

# CORRECT — iterate over a copy
for num in list(numbers):
    if num % 2 == 0:
        numbers.remove(num)
print(numbers)  # {1, 3, 5}

# CORRECT — use set comprehension
numbers = {1, 2, 3, 4, 5}
numbers = {num for num in numbers if num % 2 != 0}
print(numbers)  # {1, 3, 5}

Mistake 2: Assuming Set Order

# WRONG — sets are unordered
fruits = {"apple", "banana", "cherry"}
first = list(fruits)[0]  # Unpredictable order

# CORRECT — use sorted() for predictable order
for fruit in sorted(fruits):
    print(fruit)  # apple, banana, cherry

Mistake 3: Using pop() During Iteration Without Control

# WRONG — unpredictable behavior
numbers = {1, 2, 3, 4, 5}
# for num in numbers:
#     numbers.pop()  # Unpredictable

# CORRECT — use while loop for controlled pop
while numbers:
    element = numbers.pop()
    print(element)

Mistake 4: Forgetting sorted() Returns a List

# WRONG — sorted returns a list
fruits = {"apple", "banana", "cherry"}
sorted_fruits = sorted(fruits)
print(type(sorted_fruits))  # <class 'list'>

# CORRECT — convert back to set if needed
fruits_set = set(sorted_fruits)
# Note: order is lost when converting back to set

Quick Check: What happens if you modify a set during iteration? (Answer: RuntimeError is raised)

Interactive Editor

Experiment with set iteration techniques directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
SET ITERATION PRACTICE
========================================

Fruits: {'apple', 'banana', 'cherry', 'mango', 'orange', 'grape', 'kiwi'}
Numbers: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

1. FOR LOOP
apple
banana
cherry
mango
orange
grape
kiwi

2. SORTED ITERATION
apple
banana
cherry
grape
kiwi
mango
orange

3. SET COMPREHENSION
Squares: {1, 4, 9, 16, 25, 36, 49, 64, 81, 100}

4. FILTERED COMPREHENSION
Even squares: {4, 16, 36, 64, 100}

5. ANY() AND ALL()
Any > 5: True
All > 0: True

6. MAP()
Squares using map: {1, 4, 9, 16, 25, 36, 49, 64, 81, 100}

7. FILTER()
Even numbers using filter: {2, 4, 6, 8, 10}

Set iteration practice complete!
🏆

Certificate of Completion

You have completed the Python Set Iteration tutorial. You understand for loops, sorted iteration, set comprehension, and advanced iteration techniques for sets.

Quick Quiz — Test Your Knowledge

Test your understanding of set iteration:

1. What is the most common way to iterate over a set?
2. Is the iteration order of a set guaranteed?
3. What does sorted() return when used on a set?
4. What happens if you modify a set while iterating over it?
5. What does any() return if all elements are False?

Frequently Asked Questions

What is the best way to iterate over a set? ▼

The for loop is the most common and Pythonic way to iterate over a set. For predictable order, use sorted() before iterating.

Can I modify a set while iterating over it? ▼

No, modifying a set during iteration raises a RuntimeError. Use a copy of the set (list(my_set)) or set comprehension to safely modify it.

How do I iterate over a set in alphabetical order? ▼

Use sorted(): for item in sorted(my_set):. This returns a sorted list of elements for iteration.

What is the difference between for loop and while loop for sets? ▼

for loop is simpler and automatically handles iteration. while loop with an iterator gives more control but is less commonly used for sets.

Can I use enumerate() on a set? ▼

Yes, but the indices are arbitrary and not meaningful because sets are unordered. The indices may vary between runs.

What is set comprehension? ▼

Set comprehension is a concise way to create a new set by iterating over an existing set and applying transformations or filters. Syntax: {expression for item in set if condition}.

Where to Go From Here

After mastering set iteration, consider exploring these related topics:

Pack/Unpack Set

Learn how to pack and unpack sets with other data structures.

Learn More →

Set Comprehension

Master the powerful set comprehension technique.

Learn More →

List vs Set

Understand when to use lists and when to use sets.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
  • Top PL SQL Interview Questions
Previous: Set Methods Next: Pack/Unpack Set →