Fundamentals 6 min read

Master Python Iterators & Generators: List Comprehensions, Memory‑Efficient Loops, and Fibonacci

This article explains Python's list comprehensions, demonstrates how to create and use generators for memory‑efficient iteration, compares iterators and iterable objects, and provides practical code examples including a generator‑based Fibonacci sequence, helping readers understand and apply these core concepts in their programs.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Iterators & Generators: List Comprehensions, Memory‑Efficient Loops, and Fibonacci

Python Iterators and Generators

List Comprehensions

List comprehensions (also called list comprehensions) produce a list based on a defined rule.

list2 = [x for x in range(10)]
print(list2)

A more complex example:

list1 = [x * y for x in range(1, 5) if x > 2 for y in range(1, 4) if y < 3]

# Equivalent expanded code
list4 = []
for x in range(1, 5):
    if x > 2:
        for y in range(1, 4):
            if y < 3:
                list4.append(x * y)

Generators

Creating a list with a million elements consumes a lot of memory; a generator stores only the rule and produces elements on demand, reducing memory usage. Generators can only be iterated sequentially and cannot be indexed or rewound.

To create a generator, replace the brackets with parentheses: generator = (x for x in range(10)) A generator is a special iterator:

print("Is generator an iterator:", isinstance(generator, Iterator))  # True
print("Is generator iterable:", isinstance(generator, Iterable))    # True

Elements are retrieved with next() (or generator.__next__()) and raise StopIteration when exhausted.

Generator example for the Fibonacci sequence:

def fib(length):
    """Generator that yields a Fibonacci sequence up to the given length."""
    n, a, b = 0, 0, 1
    while n < length:
        yield b
        a, b = b, a + b
        n += 1
    return 'done'

for i in fib(10):
    print(i)

Iterators

An iterator is an object that implements the __next__() method and can be advanced with next(). Built‑in collections like list, dict, and str are iterable but not iterators. Converting an iterable to an iterator with iter() yields an object that is both an iterator and iterable.

list1 = [1, 2, 3, 4, 5, 6]
print("list1 is iterator:", isinstance(list1, Iterator))   # False
print("list1 is iterable:", isinstance(list1, Iterable))   # True

interObj = iter(list1)
print("interObj is iterator:", isinstance(interObj, Iterator))  # True
print("interObj is iterable:", isinstance(interObj, Iterable))  # False

Iterable objects are not necessarily iterators, but they are always iterable.

Iterators are always iterable; generators are a special kind of iterator.

The main difference is that iterables can report their length with len(), while iterators cannot.

Iterators provide a next() method to retrieve the next element; not all iterables have this method.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonIteratorsGeneratorslist-comprehensionmemory efficiency
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.