Convert a nested for loop to a map equivalent in Python

Nested for loops execute repetitive code blocks, where an inner loop runs completely for each iteration of the outer loop. Python's map() function provides a functional programming approach to achieve similar results by applying functions to iterables.

Understanding Nested For Loops

A nested for loop structure contains one loop inside another ?

for x in sequence:
   for y in sequence:
      # inner loop code
   # outer loop code

Map Function Syntax

map(function, iterable)

Where:

  • function: Function applied to each item in the iterable

  • iterable: Sequence like list, tuple, or set

Converting Data Types in 2D Arrays

Here's how to convert string elements to floats in a 2D array ?

# Using nested for loop
data = [['2.3', '.2'], ['-6.3', '0.9']]
print("Input:", data)

for i in range(len(data)):
    for j in range(len(data[i])):
        data[i][j] = float(data[i][j])
print("Nested for-loop output:", data)

# Using map equivalent
data = [['2.3', '.2'], ['-6.3', '0.9']]
print("\nInput:", data)
result = [list(map(float, subarray)) for subarray in data]
print("Map equivalent output:", result)
Input: [['2.3', '.2'], ['-6.3', '0.9']]
Nested for-loop output: [[2.3, 0.2], [-6.3, 0.9]]

Input: [['2.3', '.2'], ['-6.3', '0.9']]
Map equivalent output: [[2.3, 0.2], [-6.3, 0.9]]

Using Lambda with Nested Map

You can use lambda functions for more complex transformations ?

data = [['2.3', '.2'], ['-6.3', '0.9']]
print("Input:", data)

result = list(map(lambda subarray: list(map(float, subarray)), data))
print("Lambda map equivalent output:", result)
Input: [['2.3', '.2'], ['-6.3', '0.9']]
Lambda map equivalent output: [[2.3, 0.2], [-6.3, 0.9]]

Finding Prime Numbers

Converting a prime number finder from nested loops to map ?

# Using nested for loop
lower = 2
upper = 30
prime_numbers = []

for num in range(lower, upper + 1):
    if num > 1:
        is_prime = True
        for i in range(2, int(num ** 0.5) + 1):
            if num % i == 0:
                is_prime = False
                break
        if is_prime:
            prime_numbers.append(num)

print("Nested for-loop primes:", prime_numbers)

# Using map equivalent
def is_prime(n):
    if n < 2:
        return False
    return all(n % i != 0 for i in range(2, int(n ** 0.5) + 1))

map_result = list(filter(is_prime, range(lower, upper + 1)))
print("Map equivalent primes:", map_result)
Nested for-loop primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Map equivalent primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Cartesian Product Operations

Using itertools.product() to replace nested loops for combinations ?

from itertools import product

# Using nested for loop
forloop_result = []
for a in range(1, 5):
    for b in range(1, 6):
        forloop_result.append(a + b)
print("Nested for-loop output:", forloop_result)

# Using map with product
result = list(map(sum, product(range(1, 5), range(1, 6))))
print("Map equivalent output:", result)
Nested for-loop output: [2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9]
Map equivalent output: [2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9]

Comparison

Approach Readability Performance Best For
Nested For Loop More explicit Slower Complex logic, debugging
Map + Lambda Concise Faster Simple transformations
List Comprehension Pythonic Fastest Most Python scenarios

Conclusion

Converting nested for loops to map equivalents often results in more concise, functional code. Use map() with lambda for simple transformations and itertools.product() for Cartesian products. Choose the approach that balances readability and performance for your specific use case.

Updated on: 2026-03-27T06:49:04+05:30

889 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements