Hackforge Academy

Category: python

List Comprehensions

Published on 27 Oct 2026

Explanation

A list comprehension creates and stores all results immediately, allowing indexing and repeated traversal.

Code:

squares = [n*n for n in range(5)]
print(squares, squares[2], len(squares))

Explanation

A generator expression computes values lazily as they are requested.

Code:

squares = (n*n for n in range(5))
print(next(squares), next(squares))
print(list(squares))

Explanation

Generators can avoid storing a large intermediate list; the best choice depends on whether results must be retained or revisited.

Code:

values = range(1_000_000)
items = [n*2 for n in values]
gen = (n*2 for n in values)
print(len(items), next(gen))

Explanation

Generator expressions pair well with consumers such as sum(), any(), and all(), avoiding an unnecessary intermediate list.

Code:

total = sum(n*n for n in range(1, 6))
print(total)

Explanation

Choose a list when you need stored reusable results; choose a generator when incremental processing is sufficient.

Code:

values = [1, 2, 3, 4, 5]
squares = [n*n for n in values]
total = sum(n*n for n in values)
print(squares, total)

πŸš€ 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