PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Python · Theory

Generators in Python

← All stacks

Theory

86/268

Generators in Python

A generator produces values one at a time with yield. def gen(): yield 1; yield 2. for x in gen(): prints 1 then 2. It does not build a full list in memory. Generator expression: (x * x for x in range(10)) — parentheses, not brackets. yield pauses. return ends.

Contrast with list comprehension: [...] builds everything now. Generator is lazy. That memory sentence is why interviews ask. next(g) also pulls one value.

Generators in Python — output — [1, 2, 3]. yield pauses and continues — not all at once like return.

Exam tip

yield vs return in one contrast.

Example

# Generator
def count():
    yield 1
    yield 2
    yield 3

print(list(count()))

Generators in Python — output: [1, 2, 3]. yield pauses and continues — not all at once like return.

Short notes

  • Defyield values, lazy.
  • Rulefor consumes the generator.
  • Diff≠ list comprehension.

Questions

1

Explain Generators as if you are teaching a junior — definition, then one tiny script.

2

What does the example print, and why?

3

What mistake do freshers make with Generators?

Previous← Decorators in PythonNextMultiprocessing in Python →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.