Hackforge Academy

Category: python

Understanding map()

Published on 27 Oct 2026

Explanation

map() applies a function to each item and returns an iterator in Python 3.

Code:

numbers = [1, 2, 3, 4]
print(list(map(str, numbers)))

Explanation

Pass an existing function to map() to transform each input value lazily.

Code:

def square(n): return n*n
print(list(map(square, [1, 2, 3, 4])))

Explanation

A list comprehension directly builds a list and is often easy to read for simple transformations.

Code:

numbers = [1, 2, 3, 4, 5]
print([n*n for n in numbers])

Explanation

A comprehension can combine transformation and filtering in one expression.

Code:

numbers = [1, 2, 3, 4, 5, 6]
result = [n*n for n in numbers if n % 2 == 0]
print(result)

Explanation

Use map() when applying an existing function is clear; use comprehensions for concise transformations with conditions.

Code:

prices = [100, 200, 300]
def add_tax(price): return price * 1.18
print(list(map(add_tax, prices)))
print([p * 1.18 for p in prices])

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community