Python Iterators

1) Convert List to Iterator

Take a list [1,2,3], convert it to an iterator using iter(), and print each value using next().


2) Loop with Iterator

Use iter() on a list and loop through values using while + next() until StopIteration.


3) String Iterator

Create an iterator from a string "python" and print each character.


4) Tuple Iterator

Convert a tuple (10,20,30) to an iterator and print all items.


5) Dictionary Iterator

Iterate over a dictionary’s keys using iter() and next().

Example:

d = {"a":1, "b":2}

6) Iterate Over Values

Iterate values of a dictionary using iter() and next().


7) Zip Iterator

Use zip() on two lists and iterate the resulting iterator to print pairs.


8) Iterator With For Loop

Use iter() to create an iterator from a list, then loop with for to print elements.


9) StopIteration in Try/Except

Convert a list to an iterator. Use next() more times than elements and catch StopIteration.


10) Custom Iterator Class (Basic)

Create a class with __iter__() and __next__() that yields numbers 1–5.


11) Iterator That Squares

Modify #10 so the iterator yields squares: 1,4,9,16,25.


12) Infinite Iterator (Safely)

Create a class iterator that yields even numbers starting from 0. Stop after 10 items.


13) Iterator From Range

Use iter(range(1,6)) and print using next().


14) Iterator With Condition

Create an iterator that yields only even numbers from [1,2,3,4,5,6].


15) Convert Iterable to List

Use iterator + list() to convert an iterable into a list.

Example:


16) Nested Iterators

Create two iterators (list & string) and print pairs using nested loops.


17) Chaining Iterators

Use itertools.chain() to combine two lists and iterate.

(Import itertools first.)


18) Filter Iterator

Use itertools.filterfalse() to skip even numbers from a list iterator.


19) Take While Iterator

Use itertools.takewhile() to take numbers < 5 from a list iterator.


20) Custom Iterator With Reset Method

Extend a class iterator so it has a .reset() method that starts iteration over again.


🧠 Key Concepts Practiced

Concept
What You Practice

Creating an iterator

iter() on lists, strings, etc.

Consuming an iterator

next()

Handling end of iteration

catching StopIteration

Building your own iterator

implementing __iter__ & __next__

Iterator utilities

with itertools


📌 Mini Example

Simple iterator with next()

Basic custom iterator


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated