PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python Exercises » Python Loops Exercises: 40+ Coding Problems with Solutions

Python Loops Exercises: 40+ Coding Problems with Solutions

Updated on: March 24, 2026 | 327 Comments

Branching and looping techniques are essential for making decisions and controlling program flow in Python. A strong grasp of loops and conditional statements is fundamental for writing efficient, high-performance code.

This article provides 40+ Python loop practice questions that focus entirely on loops (for, while, and nested loops) and control flow statements.

Each coding challenge includes a Practice Problem, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely practice and understand how and why it works.

  • All solutions have been fully tested on Python 3.
  • Interactive Learning: Use our Online Code Editor to solve these exercises in real time.

Refer to the following tutorials to solve these exercises:

  • Control flow statements: Learn how to use if-else statements for conditional decision-making.
  • for loop: Understand how to iterate over sequences like lists, tuples, or strings.
  • range() function: Use range() within a for loop to repeat actions a specific number of times.
  • while loop: Learn to execute code blocks repeatedly as long as a specific condition remains True.
  • Break and Continue: Master these statements to dynamically alter loop execution.
  • Nested loop: Learn how to implement a loop inside another loop for complex data processing.

Also Read:

  • Python Loops Quiz
  • Python Loops Interview Questions

Let us know if you have any alternative solutions. It will help other developers.

+ Table of Contents (40 Exercises)

Table of contents

  • Exercise 1. Print first 10 natural numbers using while loop
  • Exercise 2. Display numbers from -10 to -1 using for loop
  • Exercise 3. Display a message “Done” after successful execution of for loop
  • Exercise 4. Calculate the sum of all numbers from 1 to N
  • Exercise 4. Print multiplication table of a given number
  • Exercise 6. Calculate the cube of all numbers from 1 to a given number
  • Exercise 7. Display numbers from a list using a loop
  • Exercise 8. Count occurrences of a specific element in a list
  • Exercise 9. Print elements from a list present at odd index positions
  • Exercise 10. Print list in reverse order using a loop
  • Exercise 11. Reverse a string using a for loop (no slicing)
  • Exercise 12. Count vowels and consonants in a sentence
  • Exercise 13. Count total number of digits in a number
  • Exercise 14. Reverse an integer number
  • Exercise 15. Find largest and smallest digit in a number
  • Exercise 16. Check if a number is a palindrome
  • Exercise 17. Find factorial of a number
  • Exercise 18. Collatz Conjecture: Generate a sequence until it reaches 1
  • Exercise 19. Armstrong Number Check
  • Exercise 20. Print right-angled triangle Number Pattern using a Loop
  • Exercise 21. Print the decreasing pattern
  • Exercise 22. Print the alternate numbers pattern
  • Exercise 23. Print Alphabet pyramid (A, BB, CCC) pattern
  • Exercise 24. Hollow square pattern
  • Exercise 25. Print pyramid pattern of stars
  • Exercise 26. Print full multiplication table (1 to 10)
  • Exercise 27. List Cumulative Sum: Each element is the sum of all previous
  • Exercise 28. Dictionary Filter: Extract pairs where value exceeds a threshold.
  • Exercise 29. Find common elements (Intersection) using loop
  • Exercise 30. Remove duplicates without set
  • Exercise 31. Even/Odd Segregation: Move evens to front, odds to back
  • Exercise 32. List Rotation: Rotate elements left by k positions
  • Exercise 33. Word frequency counter
  • Exercise 34. Display fibonacci series up to 10 terms
  • Exercise 35. Perfect number check
  • Exercise 36. Binary to decimal conversion using loop
  • Exercise 37. Display all prime numbers within a range
  • Exercise 38. Find the sum of the series up to n terms
  • Exercise 39. flatten a nested list using loops
  • Exercise 40. Nested list search (2D matrix coordinates)

Exercise 1. Print first 10 natural numbers using while loop

Practice Problem: Write a program to print the first 10 natural numbers using a while loop. Each number should be printed on a new line.

Exercise Purpose: This is the fundamental introduction to iteration. It teaches how to set up a loop condition to execute a block of code repeatedly, and manually manage a counter variable to prevent infinite loops.

Help: while loop in Python

Given Input: None (The range is fixed from 1 to 10).

Expected Output:

1
2
3
...
10
Hint
  • Initialize a variable i = 1.
  • Use a while loop with the condition i <= 10.
  • Don’t forget to increment i inside the loop.
Solution
# Initialize the counter
i = 1

# Iterate until i is greater than 10
while i <= 10:
    print(i)
    # Increment the counter to move to the next number
    i += 1Code language: Python (python)

Explanation to Solution:

  • i = 1: We set the starting point of our sequence.
  • while i <= 10: This creates a boundary. The code inside will keep running as long as this statement remains true.
  • i += 1: This is the “step.” Without this, i would always be 1, and the loop would never end (an infinite loop).

Exercise 2. Display numbers from -10 to -1 using for loop

Practice Problem: Write a program to display numbers from -10 to -1 using a for loop.

Exercise Purpose: This exercise focuses on Negative Indexing and Ranges. Understanding how Python handles negative numbers in the range() function is crucial for algorithms involving coordinate systems or countdowns.

Given Input: None

Expected Output:

-10
-9
...
-1
Hint

Start the range at -10 and end at 0 (since the stop value is exclusive).

Solution
# Start at -10, stop before 0
for i in range(-10, 0):
    print(i)Code language: Python (python)

Explanation to Solution:

  • range(-10, 0): In Python, range(start, stop) always goes up to, but does not include, the stop value. To include -1, we must set the stop value to 0.
  • Default Step: Even with negative numbers, the default step is +1. Adding 1 to -10 gives -9, which moves us closer to 0 as intended.

Exercise 3. Display a message “Done” after successful execution of for loop

Practice Problem: Write a program to display a message “Done” after the successful execution of a for loop that iterates from 0 to 4.

Exercise Purpose: This introduces a unique Python feature: the Loop-Else Clause. Unlike if-else, a loop else block only executes if the loop completes all its iterations without being interrupted by a break statement. This is useful for search loops to signal that a target was not found.

Given Input: None

Expected Output:

0
1
2
3
4
Done!
Hint

Place the else: block at the same indentation level as the for keyword itself.

Solution
for i in range(5):
    print(i)
else:
    # This block executes only after the loop finishes naturally
    print("Done!")Code language: Python (python)

Explanation to Solution:

  • Indentation: Notice the else is aligned with for, not print. This tells Python it belongs to the loop structure.
  • The “No Break” Rule: If we had added an if i == 3: break inside the loop, the word “Done!” would never appear. Because the loop finishes its full range (0-4), the else block is triggered.
  • Practical Use: You often use this to say “I searched the whole list and didn’t find the item.”

Exercise 4. Calculate the sum of all numbers from 1 to N

Practice Problem: Write a program that accepts a number from the user and calculates the sum of all numbers from 1 up to that number.

Exercise Purpose: This exercise teaches Value Accumulation. It shows how to use a loop to process data and store a running total in a variable, a common task in data processing.

Given Input: Enter number: 10

Expected Output: Sum is: 55

Refer:

  • Accept input from user in Python
  • Calculate sum and average in Python
Hint
  • Create a variable s = 0 before the loop.
  • Inside the loop, add the current iteration value to s using the += operator.
Solution
# Take input from user and convert to integer
n = int(input("Enter number: "))

# Variable to store the sum
s = 0

# Loop from 1 to n (n+1 is used because range is exclusive)
for i in range(1, n + 1):
    s += i

print("Sum is:", s)Code language: Python (python)

Explanation to Solution:

  • int(input(...)): We must convert the user’s string input into an integer to perform math.
  • s = 0: This is our “accumulator.” It starts empty.
  • s += i: In every step, the loop takes the current number i and adds it to our total. If n=3, it does 0+1, then 1+2, then 3+3.

Exercise 4. Print multiplication table of a given number

Practice Problem: Create a program that takes an integer and prints its multiplication table from 1 to 10.

Exercise Purpose: This reinforces the use of loops for generating Mathematical Sequences. It shows how to use the loop index (i) as a multiplier against a fixed constant.

Given Input: 2

Expected Output:

2
4
6
...
20

See: Create Multiplication Table in Python

Hint
  • Use a for loop with range(1, 11).
  • Multiply the user’s number by the current loop index in each iteration.
Solution
num = 2

# Iterate 10 times
for i in range(1, 11):
    # Calculate product
    product = num * i
    print(product)Code language: Python (python)

Explanation to Solution:

  • range(1, 11): This ensures the loop runs exactly 10 times, starting from 1 and ending at 10.
  • num * i: Since num is 2, the loop calculates 2*1, then 2*2, etc. This demonstrates how a static variable and a dynamic loop index interact.

Exercise 6. Calculate the cube of all numbers from 1 to a given number

Practice Problem: Write a program that takes an integer n and prints the cube of every number from 1 to n in the format Current Number is : 1 and the cube is 1.

Exercise Purpose: This exercise teaches Result Formatting and Power Operations. It shows how to combine text with calculated variables using f-strings or commas and perform exponentiation with the ** operator or pow() function.

Given Input: input_number = 6

Expected Output:

Current Number is : 1  and the cube is 1
Current Number is : 2 and the cube is 8
...
Current Number is : 6 and the cube is 216
Hint
  • Use a for loop with range(1, input_number + 1).
  • To calculate a cube, use i * i * i or i ** 3
Solution
input_number = 6

for i in range(1, input_number + 1):
    # Calculate cube and print with formatting
    print(f"Current Number is : {i}  and the cube is {i ** 3}")Code language: Python (python)

Explanation to Solution:

  • range(1, input_number + 1): This ensures the loop reaches the user’s number exactly.
  • i ** 3: The ** operator is Python’s way of saying “to the power of.” It is more readable than writing i * i * i for larger powers.
  • f-string (f"..."): This allows you to embed variables directly inside a string using curly braces { }, making the output code much cleaner.

Exercise 7. Display numbers from a list using a loop

Practice Problem: Given a list of numbers, iterate through it and print numbers that satisfy these conditions:

  1. The number must be divisible by five.
  2. If the number is greater than 150, skip it and move to the next.
  3. If the number is greater than 500, stop the loop entirely.

Exercise Purpose: This vital Flow Control exercise introduces continue (to skip) and break (to exit), essential for writing efficient code that avoids processing unnecessary data.

Given Input: numbers = [12, 75, 150, 180, 145, 525, 50]

Expected Output:

75
150
145

Refer: break and continue in Python

Hint
  • First, use an if statement for the “stop” condition (break)
  • Then the “skip” condition (continue), and
  • Finally, the “divisible by 5” condition.
Solution
numbers = [12, 75, 150, 180, 145, 525, 50]

for item in numbers:
    # Condition 3: Stop the loop if number > 500
    if item > 500:
        break
    
    # Condition 2: Skip the number if > 150
    if item > 150:
        continue
    
    # Condition 1: Print if divisible by 5
    if item % 5 == 0:
        print(item)Code language: Python (python)

Explanation to Solution:

  • break: When the loop hits 525, the break command kills the loop instantly. The final 50 in the list is never even checked.
  • continue: When the loop hits 180, it triggers continue. This tells Python: “Stop what you are doing for this specific number and jump back to the top of the loop for the next one.”
  • item % 5 == 0: The Modulo operator checks the remainder. If the remainder of division by 5 is 0, the number is a multiple of 5.

Exercise 8. Count occurrences of a specific element in a list

Practice Problem: Given a list of numbers, use a loop to count how many times a specific number (e.g., 10) appears.

Exercise Purpose: This introduces Frequency Counting, a staple of data analysis. It shows how to iterate through a collection and use a conditional filter to increment a tally only when a match is found.

Given Input:

list1 = [10, 20, 10, 30, 10, 40, 50]
target = 10Code language: Python (python)

Expected Output: 10 appears 3 times

Hint
  • Initialize a count = 0 variable.
  • Loop through each item in the list and check if item == target.
Solution
list1 = [10, 20, 10, 30, 10, 40, 50]
target = 10
count = 0

for num in list1:
    if num == target:
        count += 1

print(f"{target} appears {count} times")Code language: Python (python)

Explanation to Solution:

  • Direct Iteration: for num in list1 looks at each value directly, which is more “Pythonic” than using indices.
  • Conditional Increment: The count += 1 line only fires when the if condition is met.
  • Output: We use an f-string to provide a clear summary of our findings.

Exercise 9. Print elements from a list present at odd index positions

Practice Problem: Given a Python list, use a loop to print only the elements that are located at odd index positions (index 1, 3, 5, etc.).

Exercise Purpose: This exercise teaches Index-Based Iteration. It helps you distinguish between an item’s value in a list and its position (index), which is fundamental for data filtering.

Given Input: my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Expected Output: [20 40 60 80 100]

Hint

Use a for loop with range() that starts at 1 and uses a “step” of 2.

Solution
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

# range(start, stop, step)
for i in range(1, len(my_list), 2):
    print(my_list[i], end=" ")Code language: Python (python)

Explanation to Solution:

range(1, len(my_list), 2):

  • Start at the second element (odd index).
  • len(my_list): Go until the end.
  • Skip one index each time (1 -> 3 -> 5…).

my_list[i]: We use the index i generated by the range to “look up” the specific value in the list.

Exercise 10. Print list in reverse order using a loop

Practice Problem: Given a list, iterate it in reverse order and print each element.

Exercise Purpose: Learning to Traverse Data Backwards is essential for many data structures. This exercise shows how to use the reversed() function or custom range slicing to iterate over a list from the end to the beginning.

Given Input: list1 = [10, 20, 30, 40, 50]

Expected Output: [50, 40, 30, 20, 10]

Hint
  • Use the reversed() function on the list inside a for loop
  • Or use a range that starts at the last index and moves to 0 with a step of -1.
Solution
list1 = [10, 20, 30, 40, 50]

# Use the reversed() function for clean iteration
for item in reversed(list1):
    print(item)Code language: Python (python)

Solution 2: Using for loop and the len() function

list1 = [10, 20, 30, 40, 50]
size = len(list1) - 1
for i in range(size, -1, -1):
    print(list1[i])Code language: Python (python)

Explanation to Solution:

  • reversed(list1): This creates an “iterator” that yields items from the list starting from the right-most side. It is memory-efficient because it doesn’t create a new copy of the list.
  • Alternative approach: You could also use range(len(list1) - 1, -1, -1) to access the list via indices.

Exercise 11. Reverse a string using a for loop (no slicing)

Practice Problem: Write a program that takes a string and reverses it using a for loop. While Python’s [::-1] shortcut is famous, reversing a string manually is a classic way to understand how sequences are constructed.

Exercise Purpose: Learn how accumulation logic works. In Python, strings are “immutable,” which means you cannot change them directly. Here, you will practice building a new string by adding characters to the front. This is a key idea for algorithms that build results step by step.

Given Input: "Python"

Expected Output:

Original: Python
Reversed: nohtyP
Hint
  • Create an empty string reversed_str = "".
  • When you loop through the original string, add the current character to the front of your new string (char + reversed_str) instead of the back.
Solution
original_str = "Python"
reversed_str = ""

for char in original_str:
    # Prepending: Put the new character before the existing ones
    reversed_str = char + reversed_str

print(f"Original: {original_str}")
print(f"Reversed: {reversed_str}")Code language: Python (python)

Explanation to Solution:

  • char + reversed_str: This is the “flip” mechanism. If reversed_str is already “yP” and the next character is “t”, the operation t + yP results in “tyP”.
  • Immutability: Every time you perform this addition, Python creates a brand-new string in memory. This exercise highlights the cost of string operations in loops compared to lists.

Exercise 12. Count vowels and consonants in a sentence

Practice Problem: Write a program that counts the total number of vowels and consonants in a given sentence, ignoring spaces and special characters.

Exercise Purpose: In this exercise, you will practice membership testing and data filtering. You will use the in operator to check if a value is in a collection, and try string methods like .isalpha() to quickly clean your data.

Given Input: "Loops are Fun!"

Expected Output:

Vowels: 5
Consonants: 7
Hint
  • Define a string containing all vowels ("aeiou").
  • Convert the input to lowercase so you don’t have to check for capital letters separately.
  • Use if char.isalpha(): to ensure you don’t count the exclamation mark or spaces as consonants.
Solution
sentence = "Loops are Fun!"
vowels = "aeiou"
v_count = 0
c_count = 0

for char in sentence.lower():
    if char.isalpha():  # Only process letters
        if char in vowels:
            v_count += 1
        else:
            c_count += 1

print(f"Vowels: {v_count}")
print(f"Consonants: {c_count}")Code language: Python (python)

Explanation to Solution:

  • char.lower(): Normalizing the input simplifies your logic. One check handles both ‘A’ and ‘a’.
  • if char in vowels: This is a highly efficient Pythonic way to perform multiple “OR” checks (e.g., char == 'a' or char == 'e'...).
  • Nested Conditionals: The outer if filters out noise (spaces), while the inner if-else categorizes the remaining useful data.

Exercise 13. Count total number of digits in a number

Practice Problem: Write a program to count the total number of digits in a given integer using a while loop.

Exercise Purpose: This exercise introduces Arithmetic Reduction. Instead of treating the number as a string, you learn to peel off digits mathematically using floor division (//). This logic is common in algorithms involving digit manipulation, such as reversing numbers or checking for palindromes.

Given Input: 75869

Expected Output: Total digits are: 5

Hint
  • Use a while loop that continues as long as the number is not zero.
  • In each iteration, divide the number by 10 (to remove the last digit) and increment a counter.
Solution
num = 75869
count = 0

# Keep dividing by 10 until the number reaches 0
while num != 0:
    # Floor division to remove the last digit
    num = num // 10
    # Increment the counter
    count = count + 1

print("Total digits are:", count)Code language: Python (python)

Explanation to Solution:

  • num // 10: This is floor division. It divides the number by 10 and discards the remainder. For example, 75869 // 10 becomes 7586.
  • while num != 0: The loop stops once there are no more digits left to “peel off.”
  • Counter Logic: Every time the loop runs, it represents one digit processed, so we increment the count.

Exercise 14. Reverse an integer number

Practice Problem: Write a program to reverse a given integer number (e.g., 76542 should become 24567).

Exercise Purpose: While you could convert the number to a string and slice it, doing it mathematically is more efficient and teaches you to use Modulo (%) and Floor Division (//) together to manipulate digits.

Given Input: 76542

Expected Output: 24567

See: Python Programs to Reverse an Integer Number

Hint
  • Use % 10 to grab the last digit of the number.
  • Use // 10 to remove the last digit.
  • Build the reversed number by multiplying the current reverse by 10 and adding the new digit.
Solution
num = 76542
reverse_number = 0

while num > 0:
    # Get the last digit
    digit = num % 10
    # Add it to the reverse (shifting existing digits left)
    reverse_number = (reverse_number * 10) + digit
    # Remove the last digit from the original number
    num = num // 10

print(reverse_number)Code language: Python (python)

Explanation to Solution:

  • num % 10: Grabs the “remainder” of dividing by 10, which is always the last digit (e.g., 76542 -> 2).
  • reverse_number * 10: This “makes room” for the new digit by shifting the existing digits one decimal place to the left.
  • num // 10: Shaves the number down (76542 -> 7654) so the loop can process the next digit.

Exercise 15. Find largest and smallest digit in a number

Practice Problem: Write a program to find the largest and smallest digit within a given integer (e.g., in 75869, the largest is 9 and the smallest is 5).

Exercise Purpose: This combines Digit Extraction (from Exercise 14) with Min/Max Comparison. It’s a foundational logic for finding “extremes” in a dataset. You learn how to initialize comparison variables and update them dynamically as you scan through data.

Given Input: num = 75869

Expected Output:

Largest digit: 9
Smallest digit: 5
Hint
  • Initialize largest = 0 and smallest = 9.
  • Use a while loop with % 10 to get each digit.
  • Compare each digit to your current largest and smallest, updating them if a new extreme is found.
Solution
num = 75869
# Initialize with opposite extremes
largest = 0
smallest = 9

while num > 0:
    digit = num % 10
    
    # Check for new largest
    if digit > largest:
        largest = digit
    # Check for new smallest
    if digit < smallest:
        smallest = digit
        
    num = num // 10

print("Largest digit:", largest)
print("Smallest digit:", smallest)Code language: Python (python)

Explanation to Solution:

  • Initialization: We start largest at the lowest possible digit (0) and smallest at the highest (9). This ensures that the very first digit we check updates both variables.
  • if digit > largest: This is a “king of the hill” logic. If the new digit is higher than the current king, it takes the throne.
  • num // 10: We discard the last digit and move to the next until the number is exhausted.

Exercise 16. Check if a number is a palindrome

Practice Problem: Write a program to check if a given number is a palindrome. A palindrome number is a number that remains the same when its digits are reversed (e.g., 121, 343).

Exercise Purpose: This exercise combines Mathematical Reversal with Conditional Comparison. It teaches storing an original value before modifying it in a loop so you can perform a final validation.

Given Input: number = 121

Expected Output: Yes

Hint
  • Reverse the number (as shown in Exercise 14).
  • Then, use a if-else statement to compare the reversed number with the original input.
Solution
number = 121
# Store original to compare later
temp = number
reverse_num = 0

while number > 0:
    digit = number % 10
    reverse_num = (reverse_num * 10) + digit
    number = number // 10

if temp == reverse_num:
    print("Yes. Given number is palindrome number")
else:
    print("No. Given number is not palindrome")Code language: Python (python)

Explanation to Solution:

  • temp = number: Since our loop reduces number to 0, we must save the original value in temp to verify if the reversal matches.
  • Comparison Logic: The if temp == reverse_num check is the “decision point” that classifies the data.

Exercise 17. Find factorial of a number

Practice Problem: Write a program to use a loop to find the factorial of a given number (e.g., 5!). The factorial of N is the product of all integers from 1 to N.

Exercise Purpose: Factorials grow fast. This exercise demonstrates Iterative Multiplication, a core concept used in probability, statistics, and combinatorics.

Given Input: num = 5

Expected Output: 120

Hint
  • Initialize a factorial variable to 1 (not 0, or your result will always be 0!).
  • Multiply it by every number in the range from 1 to your target.
Solution
num = 5
factorial = 1

if num < 0:
    print("Factorial does not exist for negative numbers")
elif num == 0:
    print("The factorial of 0 is 1")
else:
    for i in range(1, num + 1):
        factorial = factorial * i
    print(f"The factorial of {num} is {factorial}")Code language: Python (python)

Explanation to Solution:

  • factorial = 1: This is our starting product.
  • range(1, num + 1): We iterate through 1, 2, 3, 4, 5.
  • factorial * i: The math looks like this: 1*2*3*4*5 = 120

Exercise 18. Collatz Conjecture: Generate a sequence until it reaches 1

Practice Problem: The Collatz conjecture states that if you start with any positive integer n, and if n is even, divide it by 2; if n is odd, multiply it by 3 and add 1. Repeat the process. The sequence will always eventually reach 1. Write a program to print this sequence for a given number.

Exercise Purpose: This exercise demonstrates Indeterminate Iteration. Unlike a for loop with a known range, a while loop runs until a specific mathematical condition, reaching 1, is met.

Given Input: n = 6

Expected Output: 6, 3, 10, 5, 16, 8, 4, 2, 1

Hint
  • Use while n != 1:.
  • Inside, use an if-else block to apply the n/2 or 3n+1 rules, updating n each time.
Solution
n = 6
print(n, end="")

while n != 1:
    if n % 2 == 0:
        n = n // 2
    else:
        n = (3 * n) + 1
    print(f", {n}", end="")Code language: Python (python)

Explanation to Solution:

  • while n != 1: The loop’s duration is unpredictable. For some numbers, this sequence is short; for others, it can be very long.
  • Floor Division (//): Essential here because dividing an even number by 2 should keep it as an integer, not a float (e.g., 3 instead of 3.0).

Exercise 19. Armstrong Number Check

Practice Problem: Write a program to check if a number is an Armstrong number. An Armstrong number (for a 3-digit number) is an integer such that the sum of the cubes of its digits is equal to the number itself (e.g., 153 = 1^3 + 5^3 + 3^3).

Exercise Purpose: This logic-heavy exercise combines Type Conversion, Mathematical Iteration, and Power Operations. It tests your ability to break a complex problem into steps: isolate digits, raise them to a power, and compare the sum.

Given Input: num = 153

Expected Output: Yes

Hint
  • Convert the number to a string to easily iterate over each digit.
  • Use the length of that string as the power to which you raise each digit.
Solution
num = 153
num_str = str(num)
power = len(num_str)
total = 0

for digit in num_str:
    total += int(digit) ** power

if total == num:
    print(f"{num} is an Armstrong number")
else:
    print(f"{num} is not an Armstrong number")Code language: Python (python)

Explanation to Solution:

  • str(num): Turning the number into a string is a clever “cheat” to avoid using modulo math to extract digits.
  • int(digit) ** power: We have to convert the character back into an integer to perform math. The ** operator raises it to the required power (3 for 153).
  • Validation: The final if statement compares the mathematical result against the original input to provide the verdict.

Exercise 20. Print right-angled triangle Number Pattern using a Loop

Practice Problem: Write a program to print a right-angled triangle pattern where each row contains increasing numbers up to the row number.

Exercise Purpose: This exercise introduces Nested Loops. It demonstrates how an “outer” loop can control the rows of a structure, while an “inner” loop handles the specific data printed within each row.

Given Input: None (Pattern height is 5).

Expected Output:

1 
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Refer:

  • Print Patterns In Python
  • Nested loops in Python
Hint
  • Use an outer for loop to iterate from 1 to 5.
  • Inside it, use another for loop that iterates from 1 to the current value of the outer loop index + 1.
  • In the first iteration of the outer loop, the inner loop will execute one time.
  • In the second iteration of the outer loop, the inner loop will execute two times, and so on, until row 5.
  • Print the value of j in each iteration of the inner loop (j is the inner loop iterator variable).
Solution
print("Number Pattern:")

# Outer loop for the number of rows
for i in range(1, 6):
    # Inner loop to print numbers in each row
    for j in range(1, i + 1):
        print(j, end=' ')
    # Move to the next line after each row is printed
    print("")Code language: Python (python)

Explanation to Solution:

  • range(1, 6): Generates a sequence from 1 to 5. The outer loop i represents the current row number.
  • range(1, i + 1): The inner loop depends on i. In row 3, it prints 1, 2, and 3.
  • end=' ': By default, print() adds a newline. We change it to a space so the numbers stay on the same horizontal line.
  • print(""): This empty print statement acts as a “Return” key, moving the cursor to a new line for the next row.

Exercise 21. Print the decreasing pattern

Practice Problem: Write a program to use for loop to print the following reverse number pattern:

5 4 3 2 1 
4 3 2 1
3 2 1
2 1
1

Exercise Purpose: This exercise builds on nested loops and introduces Dynamic Range Boundaries. It shows how to make the inner loop’s starting point depend on the outer loop’s current value to create decreasing structures.

Given Input: n = 5

Expected Output: (As shown in the problem description)

Refer: Print patterns in Python

Hint
  • Use an outer loop that counts down from 5 to 1.
  • The inner loop should then count down from the current outer loop value down to 1.
  • The outer loop controls the number of iterations of the inner loop. For each outer loop iteration, the number of inner loop iterations is reduced by i, the outer loop’s current number.
  • In each iteration of the inner loop, print the iterator variable of the inner loop (j).
Solution
n = 5
# Outer loop for number of rows (5 down to 1)
for i in range(n, 0, -1):
    # Inner loop for printing numbers in each row
    for j in range(i, 0, -1):
        print(j, end=' ')
    # New line after each row
    print("")Code language: Python (python)

Explanation to Solution:

  • range(5, 0, -1): The third parameter (-1) is the step. It tells Python to count backwards.
  • range(i, 0, -1): In the first row, i is 5, so it prints 5 4 3 2 1. In the second row, i is 4, so it prints 4 3 2 1.
  • Inner vs. Outer Relationship: The outer loop sets the “ceiling” for the inner loop, effectively shortening the row every time it iterates.

Exercise 22. Print the alternate numbers pattern

Practice Problem: Write a program to print a pattern of alternate numbers from 1 to 20 (e.g., 1, 3, 5…).

Exercise Purpose: This exercise emphasises Step Logic in ranges. Being able to skip values efficiently without using unnecessary if statements inside your loop makes your code more “Pythonic” and faster to execute.

Given Input: Range: 1 to 20

Expected Output: 1 3 5 7 9 11 13 15 17 19

Hint
  • The range() function takes three arguments: start, stop, and step.
  • To get every other number, set your step to 2.
Solution
# Start at 1, go up to (but not including) 21, skip by 2
for i in range(1, 21, 2):
    print(i, end=" ")Code language: Python (python)

Explanation to Solution:

  • step = 2: This tells the loop to add 2 to the current value instead of the default 1.
  • Efficiency: By using the step parameter, the loop only runs 10 times instead of 20, because it never even visits the even numbers. This is a great habit for processing large datasets where you only need a sample.

Exercise 23. Print Alphabet pyramid (A, BB, CCC) pattern

Practice Problem: Write a program to print a triangle pattern where each row consists of the same letter, and the letter changes (increments) with each new row.

Exercise Purpose: This exercise introduces ASCII Value Manipulation. You’ll learn to use the chr() function to convert numbers into characters, so you can generate the alphabet dynamically without hardcoding each letter.

Given Input: rows = 5

Expected Output:

A 
B B
C C C
D D D D
E E E E E
Hint
  • The ASCII value for ‘A’ is 65.
  • Use an outer loop to iterate from 0 to rows.
  • In each row, calculate the character using chr(65 + i) and print it i + 1 times.
Solution
rows = 5
ascii_value = 65 # Starting with 'A'

for i in range(rows):
    # Calculate current letter
    letter = chr(ascii_value + i)
    # Print the letter (i + 1) times
    for j in range(i + 1):
        print(letter, end=" ")
    print()Code language: Python (python)

Explanation to Solution:

  • chr(65 + i): As i goes from 0 to 4, this function produces ‘A’, ‘B’, ‘C’, ‘D’, and ‘E’.
  • String Multiplication (Alternative): You could also write print((letter + " ") * (i + 1)), but using a nested loop helps practice the underlying structure of grid patterns

Exercise 24. Hollow square pattern

Practice Problem: Print a 5*5 square of stars where the middle is empty, leaving only the border.

Exercise Purpose: This exercise teaches Boundary Condition Logic. Instead of printing every item in a nested loop, you use if statements to identify edges, such as the first or last rows and columns, which is essential for UI layouts and 2D array processing.

Given Input: size = 5

Expected Output:

* * * * * 
* *
* *
* *
* * * * *
Hint

Inside your nested loop, only print a star if the row index is 0 or size-1, OR if the column index is 0 or size-1. Otherwise, print a space.

Solution
n = 5
for i in range(n):
    for j in range(n):
        # Check if we are on the border
        if i == 0 or i == n - 1 or j == 0 or j == n - 1:
            print("*", end=" ")
        else:
            print(" ", end=" ")
    print()Code language: Python (python)

Explanation to Solution:

  • Logical OR (orThis allows us to combine four boundary checks into a single decision point.
  • The “Else” Space: The space in the else block is just as important as the star -it maintains the square’s shape by pushing the right-side border to the correct position.

Exercise 25. Print pyramid pattern of stars

Practice Problem: Write a program to print the following pattern using nested loops:

* 
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*

Exercise Purpose: Introduce Symmetrical Logic. It combines an increasing and a decreasing pattern. You learn to use two separate loop structures sequentially to create a complex visual shape.

Given Input: rows = 5

Expected Output: (As shown in the problem description)

Refer: Print Patterns In Python

Hint
  • Use one loop to print the top half (1 to 5 stars) and
  • A second, separate loop to print the bottom half (4 down to 1 stars).
Solution
rows = 5

# Upper part of the pattern
for i in range(0, rows):
    for j in range(0, i + 1):
        print("*", end=' ')
    print("\r")

# Lower part of the pattern
for i in range(rows - 1, 0, -1):
    for j in range(0, i):
        print("*", end=' ')
    print("\r")Code language: Python (python)

Explanation to Solution:

  • First Loop: Standard right-angled triangle logic, printing 1 to 5 stars.
  • Second Loop: The reverse. It starts at rows - 1 (4) and counts down to 0 using the step -1.
  • print("\r"): Similar to print(), it moves the cursor to the start of a new line for the next row.

Exercise 26. Print full multiplication table (1 to 10)

Practice Problem: Write a program to print the full multiplication table from 1 to 10 in a grid format.

Exercise Purpose: This is the ultimate test for Tabular Data Representation. It forces you to think about how nested loops interact. The outer loop represents the rows (multiplicands), and the inner loop represents the columns (multipliers). It also introduces the use of escape characters like \t (tab) to align text columns perfectly.

Given Input: None (Range 1-10)

Expected Output:

1	2	3	4	5	6	7	8	9	10	
2 4 6 8 10 12 14 16 18 20
...
10 20 30 40 50 60 70 80 90 100

See: Create Multiplication Table in Python

Hint
  • Use two for loops, both ranging from 1 to 11.
  • Inside the inner loop, print the product of the two loop variables, followed by a tab (\t). Use an empty print() after the inner loop to start a new row.
Solution
# Outer loop for rows
for i in range(1, 11):
    # Inner loop for columns
    for j in range(1, 11):
        # Print product followed by a tab for alignment
        print(i * j, end="\t")
    # Move to the next line after finishing a row
    print()Code language: Python (python)

Explanation to Solution:

  • range(1, 11): Both loops iterate 10 times.
  • end="\t": This is the secret to the grid layout. Instead of a newline, it inserts a tab space, keeping the cursor on the same line but neatly spaced.
  • print(): This “resets” the line. Without it, all 100 numbers would be printed in one single, massive row.

Exercise 27. List Cumulative Sum: Each element is the sum of all previous

Practice Problem: Given a list of numbers, create a new list where each element is the sum of all elements from the original list up to that position.

Exercise Purpose: This introduces the Running Total pattern. It is essentially “memory” within a loop, carrying the result of previous iterations into the current one. This logic is used in financial ledgers to calculate a balance after each transaction.

Given Input: [1, 2, 3, 4]

Expected Output:

Cumulative Sum: [1, 3, 6, 10]
Hint
  • Initialize an empty list and a variable current_sum = 0.
  • In each iteration of the loop, add the current number to current_sum and then append that sum to your new list.
Solution
numbers = [1, 2, 3, 4]
cumulative_list = []
current_sum = 0

for num in numbers:
    current_sum += num
    cumulative_list.append(current_sum)

print(f"Cumulative Sum: {cumulative_list}")Code language: Python (python)

Explanation to Solution:

  • current_sum += num: This variable acts as the “accumulator.” It grows with every step of the loop.
  • list.append(): By appending inside the loop, we capture a “snapshot” of the total at every single stage of the process.

Exercise 28. Dictionary Filter: Extract pairs where value exceeds a threshold.

Practice Problem: Given a dictionary of student scores, create a new dictionary that only includes students who scored above a certain threshold (e.g., 75).

Exercise Purpose: This exercise teaches Dictionary Iteration. Unlike lists, dictionaries have keys and values. You learn to use .items() to unpack both at once and how to conditionally build a new mapping.

Given Input:

scores = {"Alice": 85, "Bob": 70, "Charlie": 95, "David": 60} threshold = 75Code language: Python (python)

Expected Output:

Passing Students: {'Alice': 85, 'Charlie': 95}
Hint
  • Use for name, score in scores.items():.
  • Inside the loop, check if the score meets the threshold before adding it to your result dictionary.
Solution
scores = {"Alice": 85, "Bob": 70, "Charlie": 95, "David": 60}
passing_students = {}
threshold = 75

for name, score in scores.items():
    if score >= threshold:
        passing_students[name] = score

print(f"Passing Students: {passing_students}")Code language: Python (python)

Explanation to Solution:

  • .items(): This turns the dictionary into a list of pairs (tuples), allowing the loop to handle the “Who” (key) and the “How Much” (value) simultaneously.
  • Filtering: This is a classic “Search and Select” pattern used in data science to prune datasets.

Exercise 29. Find common elements (Intersection) using loop

Practice Problem: Given two lists, find the elements that appear in both. Do not use Python’s built-in set().intersection() method.

Exercise Purpose: This exercise focuses on Cross-Reference Iteration. It demonstrates how to use one collection as a master list and check its members against a secondary “filter” list to find commonalities.

Given Input:

list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]Code language: Python (python)

Expected Output: Common elements: [4, 5]

Hint
  • Create an empty list common.
  • Loop through list_a and for each item, check if item in list_b.
Solution
list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]
common = []

for item in list_a:
    if item in list_b:
        common.append(item)

print("Common elements:", common)Code language: Python (python)

Explanation to Solution:

  • The in Operator: This is a shorthand for a hidden internal loop that scans list_b for a match.
  • Filtering: This pattern is used in everything from “Suggested Friends” on social media to inventory systems checking for overlapping stock.

Exercise 30. Remove duplicates without set

Practice Problem: Write a program to remove all duplicate values from a list using a loop, maintaining the original order of elements.

Exercise Purpose: Although set(list) quickly removes duplicates, it destroys order. This exercise teaches Uniqueness Validation, ensuring each piece of data is processed once while preserving sequence.

Given Input: [1, 2, 2, 3, 4, 4, 4, 5]

Expected Output:

Unique List: [1, 2, 3, 4, 5]
Hint
  • Create a new list called unique_list.
  • As you iterate through the original list, check if the item is already in unique_list. If not, add it.
Solution
original = [1, 2, 2, 3, 4, 4, 4, 5]
unique_list = []

for num in original:
    if num not in unique_list:
        unique_list.append(num)

print("Unique List:", unique_list)Code language: Python (python)

Explanation to Solution:

  • not in: This is the inverse logic of the intersection exercise. It acts as a gatekeeper, only allowing new, unseen data to pass through.
  • Order Preservation: Because we append elements as we encounter them for the first time, the original relative order is perfectly preserved.

Exercise 31. Even/Odd Segregation: Move evens to front, odds to back

Practice Problem: Given a list of integers, move all even numbers to the beginning of the list and all odd numbers to the end.

Exercise Purpose: This introduces List Reorganization, a simplified version of the partitioning logic used in QuickSort algorithms. You learn to categorize data and reassemble it into a specific structural order.

Given Input: [1, 2, 3, 4, 5, 6]

Expected Output:

Segregated List: [2, 4, 6, 1, 3, 5]
Hint
  • Create two empty lists, evens and odds.
  • Loop through the main list, sorting numbers into their respective bins, then combine them at the end using evens + odds.
Solution
numbers = [1, 2, 3, 4, 5, 6]
evens = []
odds = []

for n in numbers:
    if n % 2 == 0:
        evens.append(n)
    else:
        odds.append(n)

# Merging lists
result = evens + odds
print("Segregated List:", result)Code language: Python (python)

Explanation to Solution:

  • Modulo Operator (% 2): The standard way to distinguish even from odd.
  • List Concatenation (+): This creates a new list by joining the two sub-lists, ensuring all evens appear before the first odd.

Exercise 32. List Rotation: Rotate elements left by k positions

Practice Problem: Given a list and an integer k, rotate the list to the left by k positions. For example, if k=2, the first two elements move to the end of the list.

Exercise Purpose: This exercise teaches Positional Manipulation. While slicing is common, using a loop helps you understand how data shifts in memory. This is a core concept for circular buffers and scheduling algorithms.

Given Input:

nums = [1, 2, 3, 4, 5]
k = 2Code language: Python (python)

Expected Output: Rotated List: [3, 4, 5, 1, 2]

Hint
  • You can perform a single rotation k times.
  • In every single rotation, remove the first element (pop(0)) and add it to the end (append()).
Solution
nums = [1, 2, 3, 4, 5]
k = 2

# Perform the rotation k times
for _ in range(k):
    # Remove the first element
    first_element = nums.pop(0)
    # Move it to the end
    nums.append(first_element)

print("Rotated List:", nums)Code language: Python (python)

Explanation to Solution:

  • pop(0): This method removes the item at the very beginning of the list and “shifts” all other items one spot to the left.
  • append(): This places that “lost” element at the very back, completing the circular movement.
  • for _ in range(k): We use an underscore _ as the variable name because we don’t actually need the index; we just need the loop to run exactly k times.

Exercise 33. Word frequency counter

Practice Problem: Write a program to count the frequency of each word in a given string.

Exercise Purpose: This introduces Mapping Logic. You learn to transform a “flat” string into a structured dictionary. This is the starting point for almost all Natural Language Processing (NLP) tasks, such as building a search engine or a tag cloud.

Given Input: text = "apple banana apple orange banana apple"

Expected Output:

{'apple': 3, 'banana': 2, 'orange': 1}
Hint
  • Use .split() to turn the string into a list of words.
  • Iterate through the list and use an if-else block to check if the word is already a key in your dictionary.
Solution
text = "apple banana apple orange banana apple"
words = text.split()
frequency = {}

for word in words:
    if word in frequency:
        frequency[word] += 1
    else:
        # First time seeing this word
        frequency[word] = 1

print(frequency)Code language: Python (python)

Explanation to Solution:

  • text.split(): By default, this splits the string at every space, yielding a list of individual strings.
  • Dictionary Check: if word in frequency checks keys, not values. If the key exists, we increment the count; if not, we create it with an initial value of 1.
  • Efficiency: This is an O(n) operation, meaning it scales linearly with the number of words.

Exercise 34. Display fibonacci series up to 10 terms

Practice Problem: Write a program to display the Fibonacci sequence up to 10 terms. The sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones.

Exercise Purpose: This exercise teaches State Management. You keep track of two changing variables (n1 and n2) and update them in sync to crawl forward through the sequence.

Given Input: n_terms = 10

Expected Output: 0 1 1 2 3 5 8 13 21 34

Refer: Generate Fibonacci Series in Python

Hint
  • Start with num1 = 0 and num2 = 1.
  • In each loop iteration, calculate the res = num1 + num2, then update num1 to be num2 and num2 to be res.
Solution
# First two terms
num1, num2 = 0, 1

print("Fibonacci sequence:")
for i in range(10):
    print(num1, end="  ")
    # Calculate next term
    res = num1 + num2
    # Update values for next iteration
    num1 = num2
    num2 = resCode language: Python (python)

Explanation to Solution:

  • num1, num2 = 0, 1: We initialize the “seed” of the sequence.
  • res = num1 + num2: This creates the new number.
  • Variable Swapping: This is the engine of the loop. By moving the value of num2 into num1, and our new res into num2, we shift our focus one step to the right for the next calculation.

Exercise 35. Perfect number check

Practice Problem: Write a program to check if a number is a “Perfect Number.” A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding the number itself). For example, 6 is perfect because 1 + 2 + 3 = 6.

Exercise Purpose: Emphasizes efficiency in search. While you could check every number up to n, you only need to check up to n/2 to find all divisors, showing how to optimize loop ranges.

Given Input: num = 28

Expected Output:

28 is a Perfect Number (1 + 2 + 4 + 7 + 14 = 28)
Hint
  • Initialize divisor_sum = 0.
  • Loop from 1 to (num // 2) + 1.
  • If num % i == 0, add i to the sum.
Solution
num = 28
divisor_sum = 0

# A divisor cannot be greater than half the number
for i in range(1, (num // 2) + 1):
    if num % i == 0:
        divisor_sum += i

if divisor_sum == num:
    print(f"{num} is a Perfect Number")
else:
    print(f"{num} is not a Perfect Number")Code language: Python (python)

Explanation to Solution:

  • num // 2: This optimization cuts the number of loop iterations in half. No number greater than 14 can evenly divide 28 (other than 28 itself).
  • num % i == 0: The modulo operator identifies “factors” or divisors.
  • Final Verdict: The comparison divisor_sum == num at the end is the logical “anchor” of the entire algorithm.

Exercise 36. Binary to decimal conversion using loop

Practice Problem: Manually convert a binary string (e.g., "1101") into its decimal integer equivalent using a loop. Do not use int(binary, 2).

Exercise Purpose: This exercise teaches Positional Notation and Powers. It helps you visualize how computers store numbers and process strings from right to left or vice versa to apply mathematical weights.

Given Input: binary_str = "1101"

Expected Output: Decimal value: 13

Hint
  • Reverse the string first.
  • Next, for each character, if it is ‘1’, add 2index to your total.
Solution
binary_str = "1101"
decimal_val = 0

# Reverse to handle indices as powers (0, 1, 2...)
reversed_binary = binary_str[::-1]

for i in range(len(reversed_binary)):
    if reversed_binary[i] == '1':
        decimal_val += 2 ** i

print("Decimal value:", decimal_val)Code language: Python (python)

Explanation to Solution:

  • [::-1]: We reverse the string so that the index i matches the power of 2 (the rightmost digit is 20).
  • 2 ** i: This calculates the “weight” of the current position.

Calculation for “1101”:

  • ( 1.20 ) + ( 0.21 ) + ( 1.22 ) + ( 1.23 )
  • 1 + 0 + 4 + 8 = 13.

Exercise 37. Display all prime numbers within a range

Practice Problem: Write a program to display all prime numbers within a range (e.g., 25 to 50). A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers.

Exercise Purpose: This is a classic test of Nested Loop Logic. You iterate through a range of numbers (outer loop) and, for each, run another loop (inner loop) to check if any smaller number divides it evenly. It’s excellent for practicing flag variables or the loop-else construct

Given Input: start = 25, end = 50

Expected Output:

Prime numbers between 25 and 50 are:
29
31
37
41
43
47

See: Python Programs to Find Prime Numbers within a Range

Hint
  • For every number in the range, try dividing it by all numbers from 2 up to the square root of that number (or just half of it).
  • If any division results in a remainder of 0, it’s not prime.
Solution
start = 25
end = 50

print(f"Prime numbers between {start} and {end} are:")

for num in range(start, end + 1):
    # Prime numbers are greater than 1
    if num > 1:
        for i in range(2, num):
            if (num % i) == 0:
                # Found a factor, not prime
                break
        else:
            # Loop finished without finding a factor
            print(num)Code language: Python (python)

Explanation to Solution:

  • if num > 1: Basic rule of primes; we ignore 0, 1, and negative numbers.
  • range(2, num): The inner loop checks every possible divisor.
  • break: As soon as we find one factor (e.g., 25 \ 5), we stop checking that number-it’s already disqualified.
  • else: Using the “loop-else” here is very clever. The else block only runs if the break was never triggered, meaning the number is prime.

Exercise 38. Find the sum of the series up to n terms

Practice Problem: Write a program to calculate the sum of the series 2 + 22 + 222 + 2222 + …. up to N terms. For example, if n=5, the series is 2 + 22 + 222 + 2222 + 22222.

Exercise Purpose: This advanced Pattern Accumulation exercise requires generating a new number at each step by multiplying the previous number by 10, adding 2, and then adding that result to a running total.

Given Input:

number_of_terms = 5

Expected Output: 24690

Hint
  • Start with start = 2 and total_sum = 0.
  • In each step, add start to total_sum, then update start by calculating start * 10 + 2.
Solution
n = 5
start = 2
sum_seq = 0

for i in range(0, n):
    # Add current term to the total sum
    sum_seq += start
    # Generate the next term (e.g., 2 -> 22 -> 222)
    start = start * 10 + 2

print(sum_seq)Code language: Python (python)

Explanation to Solution:

  • start = start * 10 + 2: This is the “growth engine.” If start is 22, multiplying by 10 makes it 220, and adding 2 makes it 222.
  • sum_seq += start: We keep a running tally of these growing numbers.
  • Iteration Logic: The loop runs n times to ensure we process exactly the requested number of terms.

Exercise 39. flatten a nested list using loops

Practice Problem: Given a nested list (a list containing other lists), write a program to “flatten” it into a single list containing all the individual elements.

Exercise Purpose: In data science and web development, data often arrives in “nested” formats (like JSON). This exercise teaches you Dimensionality Reduction. You learn how to “reach inside” one container to pull items out and place them into a new, simpler container.

Given Input: nested_list = [[10, 20], [30, 40], [50, 60]]

Expected Output: [10, 20, 30, 40, 50, 60]

Hint
  • Create an empty list called flattened.
  • Use an outer for loop to iterate through the main list, and an inner for loop to iterate through each sub-list, appending every item to your flattened list.
Solution
nested_list = [[10, 20], [30, 40], [50, 60]]
flattened = []

# Iterate through each sub-list
for sublist in nested_list:
    # Iterate through each item in the current sub-list
    for item in sublist:
        flattened.append(item)

print("Flattened List:", flattened)Code language: Python (python)

Explanation to Solution:

  • for sublist in nested_list: The first loop picks up [10, 20].
  • for item in sublist: The second loop looks inside that sub-list and picks up 10, then 20.
  • .append(item): This adds the individual numbers to our new flat list one by one. By the time the outer loop finishes, all nested items have been “promoted” to the main list.

Exercise 40. Nested list search (2D matrix coordinates)

Practice Problem: Given a 2D list (matrix), find the row and column index of a target value.

Exercise Purpose: This is the foundation of Coordinate Systems. You learn to use nested loops, where the outer loop iterates over rows, and the inner loop iterates over columns. This logic is essential for game development, image processing, and spreadsheet automation.

Given Input:

matrix = [[10, 20], [30, 40], [50, 60]]
target = 30Code language: Python (python)

Expected Output:

Target 30 found at Row: 1, Column: 0
Hint
  • Use enumerate() on the outer loop to get the row index, and enumerate() on the inner loop to get the column index.
Solution
matrix = [
    [10, 20],
    [30, 40],
    [50, 60]
]
target = 30

for r_idx, row in enumerate(matrix):
    for c_idx, val in enumerate(row):
        if val == target:
            print(f"Target {target} found at Row: {r_idx}, Column: {c_idx}")
            break # Found it!Code language: Python (python)

Explanation to Solution:

  • enumerate(): This is a cleaner way to get both the index and the item at the same time, avoiding the clunky range(len()) syntax.
  • Nested Loops: The outer loop picks a row; the inner loop “scans” across that row.
  • The break: Since we only need one occurrence, break stops the inner loop immediately once the target is found to save time.

Filed Under: Python, Python Basics, Python Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics Python Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Loading comments... Please wait.

In: Python Python Basics Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercises for Beginners
  • Intermediate Python Exercises
  • Input and Output Exercises
  • Loop Exercises
  • Functions Exercises
  • String Exercises
  • List Exercises
  • Dictionary Exercises
  • Set Exercises
  • Tuple Exercises
  • Data Structure Exercises
  • Date and Time Exercises
  • OOP Exercises
  • File Handling Exercises
  • Iterators & Generators Exercises
  • Regex Exercises
  • Python JSON Exercises
  • Random Data Generation Exercises
  • NumPy Exercises
  • Pandas Exercises
  • Matplotlib Exercises
  • Python Database Exercises

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com