Add and subtract days

Add and subtract days

EasyDatetime Programs · 4 of 20

Write a Python program to find the dates 30 days after and 7 days before a date.

Output
2026-12-02 2026-10-26

Approach

  1. Add or subtract a timedelta.

Solution

Python
from datetime import date, timedelta d = date(2026, 11, 2)print(d + timedelta(days=30), d - timedelta(days=7))
Output
2026-12-02 2026-10-26

Learn the concept

New to this topic? Read the lesson, then come back.

More datetime programs

← All 20 Datetime Programs

Format a date

Format a date

EasyDatetime Programs · 2 of 20

Write a Python program to print a date in several formats.

Output
%d-%m-%Y   02-11-2026
%d/%m/%y   02/11/26
%B %d, %Y  November 02, 2026
%a %d %b   Mon 02 Nov

Approach

  1. strftime codes.

Solution

Python
from datetime import date d = date(2026, 11, 2)for fmt in ["%d-%m-%Y", "%d/%m/%y", "%B %d, %Y", "%a %d %b"]:    print(fmt.ljust(10), d.strftime(fmt))
Output
%d-%m-%Y   02-11-2026
%d/%m/%y   02/11/26
%B %d, %Y  November 02, 2026
%a %d %b   Mon 02 Nov

Learn the concept

New to this topic? Read the lesson, then come back.

More datetime programs

← All 20 Datetime Programs

Parse a date string

Parse a date string

EasyDatetime Programs · 3 of 20

Write a Python program to convert the string “15/08/2026 09:30” into a datetime.

Output
2026-08-15 09:30:00 Saturday

Approach

  1. datetime.strptime(text, format).

Solution

Python
from datetime import datetime dt = datetime.strptime("15/08/2026 09:30", "%d/%m/%Y %H:%M")print(dt, dt.strftime("%A"))
Output
2026-08-15 09:30:00 Saturday

Learn the concept

New to this topic? Read the lesson, then come back.

More datetime programs

← All 20 Datetime Programs

Python Iterator & Generator Programs with Solutions

Python Practice › Iterator & Generator Programs

Python Iterator & Generator Programs with Solutions

20 programs16 easy4 medium0 hard

20 iterator and generator programs: iter() and next(), custom iterator classes, generator functions with yield, generator expressions, infinite sequences, pipelines and itertools.

Before you start

Read the Iterators and Generators lesson first if the topic is new to you.

All programs

Create a date and read its parts

Create a date and read its parts

EasyDatetime Programs · 1 of 20

Write a Python program to create a date and print its year, month, day and weekday.

Output
2026-11-02 2026 11 2 Monday

Approach

  1. date(y, m, d) and its attributes.

Solution

Python
from datetime import date d = date(2026, 11, 2)print(d, d.year, d.month, d.day, d.strftime("%A"))
Output
2026-11-02 2026 11 2 Monday

Learn the concept

New to this topic? Read the lesson, then come back.

More datetime programs

← All 20 Datetime Programs

Group consecutive items

Group consecutive items

EasyIterator & Generator Programs · 20 of 20

Write a Python program that groups log lines by level with itertools.groupby.

Output
ERROR ['db', 'disk']
INFO ['ok', 'start']

Approach

  1. groupby groups consecutive equal keys, so sort first.

Solution

Python
from itertools import groupby logs = [("ERROR", "db"), ("INFO", "start"), ("ERROR", "disk"), ("INFO", "ok")]for level, group in groupby(sorted(logs), key=lambda x: x[0]):    print(level, [msg for _, msg in group])
Output
ERROR ['db', 'disk']
INFO ['ok', 'start']

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Send values into a generator

Send values into a generator

MediumIterator & Generator Programs · 18 of 20

Write a generator that keeps a running average of values sent to it.

Output
10.0 15.0 30.0

Approach

  1. value = yield result receives what send() passes.

Solution

Python
def averager():    total, count, average = 0, 0, None    while True:        value = yield average        total += value        count += 1        average = total / count avg = averager()next(avg)                      # start the generatorprint(avg.send(10), avg.send(20), avg.send(60))
Output
10.0 15.0 30.0

Line by line

Line 4

The generator pauses here, hands out the current average and waits for the next value.

Line 10

The first next() runs the code up to the first yield.

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Take values while a condition holds

Take values while a condition holds

EasyIterator & Generator Programs · 19 of 20

Write a Python program that takes Fibonacci numbers while they are below 100.

Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Approach

  1. itertools.takewhile.

Solution

Python
from itertools import takewhile def fibonacci():    a, b = 0, 1    while True:        yield a        a, b = b, a + b print(list(takewhile(lambda n: n < 100, fibonacci())))
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Generator vs list memory

Generator vs list memory

EasyIterator & Generator Programs · 17 of 20

Write a Python program that compares the memory of a list and a generator of a million numbers.

Output
True True

Approach

  1. sys.getsizeof.

Solution

Python
import sys as_list = [n for n in range(1_000_000)]as_gen = (n for n in range(1_000_000))print(sys.getsizeof(as_list) > 1_000_000, sys.getsizeof(as_gen) < 1_000)
Output
True True
Note

The exact byte counts depend on the Python version, so the program prints comparisons.

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Iterators from zip and enumerate

Iterators from zip and enumerate

EasyIterator & Generator Programs · 16 of 20

Write a Python program that shows zip and enumerate return iterators.

Output
('a', 1)
[('b', 2), ('c', 3)]
[(1, 'x'), (2, 'y')] []

Approach

  1. Call next() on them and see the rest continue.

Solution

Python
pairs = zip(["a", "b", "c"], [1, 2, 3])print(next(pairs))print(list(pairs))numbered = enumerate(["x", "y"], start=1)print(list(numbered), list(numbered))
Output
('a', 1)
[('b', 2), ('c', 3)]
[(1, 'x'), (2, 'y')] []

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs