---
title: "Explain the Python Iterators"  
description: "Explain the Python Iterators"  
author: "ICSM Computer"  
published: 2025-10-02  
updated: 2025-10-02  
canonical: https://www.mindstick.com/interview/34384/explain-the-python-iterators  
category: "python"  
tags: ["python-3.4", "Python 3"]  
reading_time: 4 minutes  

---

# Explain the Python Iterators

> ### What is an Iterator?
>
> An **iterator** in Python is an object that lets you loop through a sequence (like a list, tuple, or string) one element at a time, without needing to store the whole sequence in memory.

It follows the **iterator protocol**, which means it must implement two methods:

- `__iter__()` → returns the iterator object itself.
- `__next__()` → returns the next item in the sequence. If no items are left, it raises a `StopIteration` exception.

### Example 1: Basic Iterator

```python
numbers = [1, 2, 3]
it = iter(numbers)  # create an iterator

print(next(it))  # 1
print(next(it))  # 2
print(next(it))  # 3
# print(next(it))  # raises StopIteration
```

Here, `iter()` turns the list into an iterator, and `next()` fetches items one by one.

### Example 2: Custom Iterator

You can build your own iterator class by defining `__iter__()` and `__next__()`:

```python
class CountUpTo:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0

    def __iter__(self):
        return self  # an iterator must return itself

    def __next__(self):
        if self.current < self.limit:
            self.current += 1
            return self.current
        else:
            raise StopIteration

counter = CountUpTo(3)
for num in counter:
    print(num)
```

Output:

```plaintext
1
2
3
```

### Why Iterators Matter

- **Memory efficiency**: They don’t load everything at once (useful for large datasets).
- **Lazy evaluation**: Items are produced only when needed.
- **Works with loops**: `for` loops, comprehensions, and many built-ins use iterators under the hood.

### Iterators vs Iterables

- **Iterable**: Any object you can loop over (like list, tuple, dict, string). It has `__iter__()`.
- **Iterator**: The actual object that produces values one by one. It has both `__iter__()` and `__next__()`.

Example:

```python
nums = [1, 2, 3]   # iterable
it = iter(nums)    # iterator
```

> An **iterator** is like a TV remote. The `__next__()` button gets you the next channel (item). Once you reach the end, pressing it again gives you a "no signal" (`StopIteration`).

## Answers

### Answer by ICSM Computer

> ### What is an Iterator?
>
> An **iterator** in Python is an object that lets you loop through a sequence (like a list, tuple, or string) one element at a time, without needing to store the whole sequence in memory.

It follows the **iterator protocol**, which means it must implement two methods:

- `__iter__()` → returns the iterator object itself.
- `__next__()` → returns the next item in the sequence. If no items are left, it raises a `StopIteration` exception.

### Example 1: Basic Iterator

```python
numbers = [1, 2, 3]
it = iter(numbers)  # create an iterator

print(next(it))  # 1
print(next(it))  # 2
print(next(it))  # 3
# print(next(it))  # raises StopIteration
```

Here, `iter()` turns the list into an iterator, and `next()` fetches items one by one.

### Example 2: Custom Iterator

You can build your own iterator class by defining `__iter__()` and `__next__()`:

```python
class CountUpTo:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0

    def __iter__(self):
        return self  # an iterator must return itself

    def __next__(self):
        if self.current < self.limit:
            self.current += 1
            return self.current
        else:
            raise StopIteration

counter = CountUpTo(3)
for num in counter:
    print(num)
```

Output:

```plaintext
1
2
3
```

### Why Iterators Matter

- **Memory efficiency**: They don’t load everything at once (useful for large datasets).
- **Lazy evaluation**: Items are produced only when needed.
- **Works with loops**: `for` loops, comprehensions, and many built-ins use iterators under the hood.

### Iterators vs Iterables

- **Iterable**: Any object you can loop over (like list, tuple, dict, string). It has `__iter__()`.
- **Iterator**: The actual object that produces values one by one. It has both `__iter__()` and `__next__()`.

Example:

```python
nums = [1, 2, 3]   # iterable
it = iter(nums)    # iterator
```

> An **iterator** is like a TV remote. The `__next__()` button gets you the next channel (item). Once you reach the end, pressing it again gives you a "no signal" (`StopIteration`).


---

Original Source: https://www.mindstick.com/interview/34384/explain-the-python-iterators

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
