HelpContactFor teachers and institutes
>_StemPy Lab
Mock TestsClasses

>_StemPy Lab

Learn. Solve. Code the solutions. Test yourself.

Live examsFree mock exams, timed and rankedEveryone starts together, and your score and rank come the moment it ends.See the exams →
Live examsInternational live exams are comingTell us which exam you want first. Timed practice papers are open now.See what is coming →

Learn

  • Physics
  • Chemistry
  • Mathematics
  • Biology
  • Python Programming
  • Statistics & Data Science
  • Computer Science
  • Space Science and Astronomy
  • Earth and Environmental Science
  • Classes
  • Groups

Practice

  • Problems
  • Quizzes
  • Mock Tests
  • Prepare for an Exam
  • Question Sets
  • Exams
  • Certificates
  • Python Labs
  • AI Practice Generator
  • Student-Created Tests

Community

  • Discussions
  • Resources
  • Notes
  • Glossary
  • Blog

Account

  • Log in
© 2026 senLearn. All rights reserved.HelpFor SchoolsAboutContactPrivacy PolicyTerms of UseRefund Policy
  1. Python Programming
  2. /Python Going Further
  3. /Comprehensions, Iterators and Generators

Comprehensions, Iterators and Generators

Python Programming · High School (11–12) · 1 course, 11 worked problems, 31 practice questions

Python often lets you build a list in one clear line. The list comprehension [x * x for x in range(10)] makes the squares of 0 to 9, and an if at the end filters the items. Dictionary and set comprehensions work in the same way. An iterator gives items one at a time, and every for loop uses one. A generator is a function that uses yield to hand out values one by one instead of building a whole list. It saves memory, so it suits very long or endless sequences, such as the prime numbers.

With practice you will be able to

  • Write a list comprehension that maps and filters a list
  • Write a generator function with yield
  • Explain why a generator uses less memory than a list

On the syllabus of

  • Python Certification

Lessons

  • Comprehensions, Iterators and GeneratorsWhat does a for loop really do? Can a generator give numbers for ever?High School (11–12)

Practice questions

Choose an answer, then check it. Each one shows a full explanation.

A list comprehension with two for parts builds a small deck of card objects. class Card: def __init__(self, rank, suit): self.rank = rank self.suit = suit def __str__(self): return self.rank + self.suit deck = [Card(r, s) for s in "HS" for r in "AK"] print([str(c) for c in deck], len([c for c in deck if c.suit == "S"])) What does the program print?

An iterator is made from a string. One value is taken with next, and a list comprehension uses the rest. it = iter("python") first = next(it) rest = [ch for ch in it if ch != "h"] print(first, rest, next(it, "end")) What does the program print?

A generator expression is tested with in, and then turned into a list. squares = (n * n for n in range(6)) print(9 in squares, list(squares)) What does the program print?

Worked problems

Each one has a hint, the key idea and a full worked solution.

  • Write each loop as a list comprehension.Easy
  • Write this comprehension as a plain loop, and say what it gives for numbers = [1, 2, 3, 4, 5].Easy
  • The matrix is m = [[1, 2], [3, 4], [5, 6]], three rows of two…Medium
  • Given names = ["Asha", "Ravi", "Meera"] and marks = [72, 85, 64], use zip and a comprehension to…Easy
  • Any or all?Easy
  • A list of pairs students = [("Asha", 72), ("Ravi", 85), ("Meera", 72), ("Kabir", 90)]…

Python labs

  • Comprehension drills
  • Dictionary and set comprehensions
  • Build an iterator class
  • Write a generator
  • Project: the pipeline

Related topics

  • Python Going Further
  • Classes and Objects
  • Inheritance and Special Methods
  • Files and Data Formats
  • Data Structures
  • Testing and Debugging

A generator function gives the characters of a text up to a stop character, and then ends with return. def upto(text, stop): for ch in text: if ch == stop: return yield ch print("".join(upto("data,science", ",")), list(upto("abc", "z")), list(upto(",x", ","))) What does the program print?

A list comprehension and a lambda work on the words of a sentence. words = "the quick brown fox jumps".split() long = [w[0].upper() for w in words if len(w) > 3] print("".join(long), sorted(words, key=lambda w: w[-1])[0]) What does the program print?

A generator function gives the capital letters of a text, as small letters. def capitals(text): for ch in text: if ch.isupper(): yield ch.lower() g = capitals("PyCharm IDE") first = next(g) rest = list(g) print(first, rest, list(g)) What does the program print?

Two generator functions work one after the other on a shopping list. def parts(text): for part in text.split(";"): yield part.strip() def numbered(items): n = 0 for item in items: if item: n += 1 yield str(n) + "." + item print(list(numbered(parts("milk; ;eggs;bread ")))) What does the program print?

A list comprehension uses a conditional expression, and filter is called with None. vals = [x if x % 3 else 0 for x in range(1, 7)] print(vals, list(filter(None, vals))) What does the program print?

A nested list comprehension builds a grid, and a second one counts some of its numbers. grid = [[r * c for c in range(3) if c != r] for r in range(1, 4)] print(grid, len([x for row in grid for x in row if x % 2])) What does the program print?

A generator function gives the even numbers below n. def evens(n): for k in range(n): if k % 2 == 0: yield k g = evens(7) print(next(g), sum(g), list(g), sum(evens(7))) What does the program print?

All 31 practice questions on Comprehensions, Iterators and Generators →

Medium
  • For each, say whether it is an iterable that is not an iterator, or an iterator, and whether it can…Easy
  • Used upMedium
  • Follow the generatorMedium
  • Write an endless generator squares() that gives 1, 4, 9, 16,..…Medium
  • Write an endless generator primes() that gives 2, 3, 5, 7, 11,..…Hard