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 For Each Loop: Practice Assignments

Python For Each Loop Practice Assignments

Master for each loop iteration with lists, tuples, dictionaries, sets, and strings.

Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers to make programming easy through practical examples and clear explanations.
šŸ“‘ On this page:
  • About
  • Lists
  • Tuples
  • Dictionaries
  • Sets
  • Strings
  • Advanced
  • Try It
Share:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link

About These Assignments

This page contains 30+ practice assignments covering for each loop iteration in Python. You'll work with lists, tuples, dictionaries, sets, strings, and advanced iteration techniques.

🟢 Beginner 🟠 Intermediate šŸ”“ Advanced

šŸ’” Tip: Try each problem yourself first. Click "Show Solution" only after attempting.

1. Iterating Over Lists 5 Questions

šŸŽÆ Learning Goal: Master list iteration using for each loop.
Beginner Q1: Print List Elements
Iterate over a list of fruits and print each fruit name.
šŸ’” Solution:
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
for fruit in fruits:
print(fruit)
šŸ“– Explanation: The for loop iterates through each element in the list.
Beginner Q2: Sum of List
Calculate the sum of all numbers in a list using a for each loop.
šŸ’” Solution:
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
total += num
print(f"Sum: {total}")
šŸ“– Explanation: Accumulates the sum by iterating through each element.
Intermediate Q3: Find Maximum
Find the maximum value in a list without using max().
šŸ’” Solution:
numbers = [34, 78, 12, 99, 56, 23]
max_val = numbers[0]
for num in numbers:
if num > max_val:
max_val = num
print(f"Maximum: {max_val}")
šŸ“– Explanation: Compares each element to find the maximum.
Intermediate Q4: Square Each Element
Create a new list containing squares of each element from the original list.
šŸ’” Solution:
numbers = [1, 2, 3, 4, 5]
squares = []
for num in numbers:
squares.append(num ** 2)
print(squares)
šŸ“– Explanation: Uses list append within the loop to build a new list.
Advanced Q5: Filter Even Numbers
Create a new list containing only even numbers from the original list.
šŸ’” Solution:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = []
for num in numbers:
if num % 2 == 0:
evens.append(num)
print(evens)
šŸ“– Explanation: Uses conditional check to filter elements.

2. Iterating Over Tuples 3 Questions

šŸŽÆ Learning Goal: Master tuple iteration using for each loop.
Beginner Q6: Print Tuple Elements
Iterate over a tuple of colors and print each color.
šŸ’” Solution:
colors = ("red", "green", "blue", "yellow")
for color in colors:
print(color)
šŸ“– Explanation: Tuples are iterable just like lists.
Intermediate Q7: Tuple of Numbers - Sum and Product
Calculate the sum and product of numbers in a tuple.
šŸ’” Solution:
nums = (2, 3, 4, 5)
total = 0
product = 1
for n in nums:
total += n
product *= n
print(f"Sum: {total}, Product: {product}")
šŸ“– Explanation: Iterates through tuple to compute sum and product.
Advanced Q8: Tuple Unpacking in Loop
Iterate over a list of tuples and unpack each tuple into variables.
šŸ’” Solution:
students = [("Alice", 25), ("Bob", 22), ("Charlie", 28)]
for name, age in students:
print(f"{name} is {age} years old")
šŸ“– Explanation: Tuple unpacking in the for loop makes code cleaner.

3. Iterating Over Dictionaries 4 Questions

šŸŽÆ Learning Goal: Master dictionary iteration using for each loop.
Beginner Q9: Print Dictionary Keys and Values
Iterate over a dictionary and print each key and value.
šŸ’” Solution:
person = {"name": "John", "age": 30, "city": "New York"}
for key, value in person.items():
print(f"{key}: {value}")
šŸ“– Explanation: items() returns key-value pairs for iteration.
Intermediate Q10: Sum of Dictionary Values
Calculate the sum of all values in a dictionary.
šŸ’” Solution:
scores = {"math": 90, "science": 85, "english": 88, "history": 92}
total = 0
for score in scores.values():
total += score
print(f"Total: {total}")
šŸ“– Explanation: values() returns an iterable of dictionary values.
Advanced Q11: Find Key with Maximum Value
Find the key with the maximum value in a dictionary.
šŸ’” Solution:
scores = {"math": 90, "science": 85, "english": 88, "history": 92}
max_key = ""
max_val = -1
for key, value in scores.items():
if value > max_val:
max_val = value
max_key = key
print(f"Highest: {max_key} with {max_val}")
šŸ“– Explanation: Tracks key with maximum value during iteration.

4. Iterating Over Sets 2 Questions

šŸŽÆ Learning Goal: Master set iteration using for each loop.
Beginner Q12: Print Set Elements
Iterate over a set of numbers and print each element.
šŸ’” Solution:
numbers = {10, 20, 30, 40, 50}
for num in numbers:
print(num)
šŸ“– Explanation: Sets are iterable, but order is not guaranteed.
Intermediate Q13: Set Operations in Loop
Find the sum and average of elements in a set.
šŸ’” Solution:
nums = {5, 10, 15, 20, 25}
total = 0
for n in nums:
total += n
avg = total / len(nums)
print(f"Sum: {total}, Average: {avg}")
šŸ“– Explanation: Iterates through set to compute statistics.

5. Iterating Over Strings 3 Questions

šŸŽÆ Learning Goal: Master string iteration using for each loop.
Beginner Q14: Print Each Character
Iterate over a string and print each character.
šŸ’” Solution:
word = "Python"
for char in word:
print(char)
šŸ“– Explanation: Strings are iterable character by character.
Intermediate Q15: Count Vowels
Count the number of vowels in a string.
šŸ’” Solution:
text = "Hello World"
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
print(f"Vowels: {count}")
šŸ“– Explanation: Iterates through string and checks for vowels.

6. Advanced Iteration 3 Questions

šŸŽÆ Learning Goal: Master advanced for each loop techniques.
Advanced Q16: Nested Iteration
Iterate over a list of lists and print each element.
šŸ’” Solution:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
print(element, end=' ')
print()
šŸ“– Explanation: Nested for loops to iterate through 2D structure.
Advanced Q17: enumerate() Usage
Use enumerate() to get index and value while iterating.
šŸ’” Solution:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
šŸ“– Explanation: enumerate() provides index along with value.
Advanced Q18: zip() for Parallel Iteration
Iterate over two lists in parallel using zip().
šŸ’” Solution:
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
šŸ“– Explanation: zip() pairs elements from multiple iterables.

Try It Yourself!

Use the interactive editor below to test your solutions or write your own for each loop code.

Loading Pyodide... 0%
Python Code Editor
========================================
FOR EACH LOOP PRACTICE
========================================
Fruits:
- apple
- banana
- cherry
Person Details:
name: Alice
age: 25
city: NYC
Characters in 'Python':
P y t h o n

āœ… Write your for each loop solutions here!

šŸ“š Related Tutorials

šŸ”„ For Each Loop

Learn about for each loop in Python

šŸ” For Loop

Learn about for loops in Python

šŸ“ All Loops Assignments

More loop practice problems

šŸ“– Related Tutorials
  • For Loop Examples
  • While Loop
  • Break, Continue, Else
  • For vs While
  • Iterate List
  • Iterate Dictionary
Previous: For Each Loop Next: All Loops Assignments →