tensorflow
iterator
getnext
error-handling
machine-learning

Tensorflow GetNext failed because the iterator has not been initialized

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

This error is a TensorFlow 1 style dataset issue. It means your code called iterator.get_next() on an initializable iterator before running the iterator’s initializer in the session.

Why the Error Happens

In TensorFlow 1 graph mode, an initializable iterator is just another graph object until you explicitly initialize it. Creating the dataset and the iterator does not automatically prepare it for reading.

The basic pattern looks like this:

python
1import tensorflow as tf
2
3tf.compat.v1.disable_eager_execution()
4
5dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]).batch(2)
6iterator = tf.compat.v1.data.make_initializable_iterator(dataset)
7next_element = iterator.get_next()

At this point next_element exists in the graph, but the iterator still has no runtime state. If you try to fetch next_element immediately, TensorFlow raises the “iterator has not been initialized” error.

Initialize the Iterator Before Reading

The fix is to run iterator.initializer inside the session before calling get_next():

python
1import tensorflow as tf
2
3tf.compat.v1.disable_eager_execution()
4
5dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]).batch(2)
6iterator = tf.compat.v1.data.make_initializable_iterator(dataset)
7next_element = iterator.get_next()
8
9with tf.compat.v1.Session() as sess:
10    sess.run(iterator.initializer)
11
12    print(sess.run(next_element))
13    print(sess.run(next_element))

Once initialized, the iterator can produce batches until the dataset is exhausted.

Reinitialize When the Dataset Changes

Initializable iterators are often used when the dataset depends on placeholders or when the same iterator should be reused for multiple epochs. In those cases, initialization is not a one-time idea. It is part of the iteration lifecycle.

For example:

python
1with tf.compat.v1.Session() as sess:
2    for epoch in range(3):
3        sess.run(iterator.initializer)
4        try:
5            while True:
6                print(sess.run(next_element))
7        except tf.errors.OutOfRangeError:
8            pass

This pattern resets the iterator for each epoch. Without the reinitialization, the iterator stays exhausted after the first full pass.

Use One-Shot or Python Iteration in Modern Code

If you do not need explicit control, TensorFlow 1 also had one-shot iterators that did not require manual initialization. In TensorFlow 2, the normal style is even simpler: iterate over the dataset directly in eager execution.

TensorFlow 2 style:

python
1import tensorflow as tf
2
3dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]).batch(2)
4
5for batch in dataset:
6    print(batch.numpy())

This is why the error mostly appears in older graph-mode code or migration code that still uses tf.compat.v1.

Mixing TensorFlow 1 and TensorFlow 2 Concepts

The error becomes especially confusing when code mixes TensorFlow 1 graph concepts with TensorFlow 2 expectations. For example, calling disable_eager_execution() or using tf.compat.v1.data.make_initializable_iterator means you are back in the world where manual iterator initialization matters.

If the codebase is meant to stay in TensorFlow 2, the cleaner fix is often to remove the old iterator pattern entirely and use direct dataset iteration or Keras input pipelines.

Common Pitfalls

The most common mistake is creating an initializable iterator and assuming it behaves like a one-shot iterator. It does not. It must be initialized explicitly in the session.

Another pitfall is initializing the iterator only once and forgetting that it may need to be reinitialized for each epoch or each new dataset feed.

It is also easy to overlook the execution mode. If the program uses tf.compat.v1 graph mode, iterator setup rules are very different from TensorFlow 2 eager iteration.

Finally, do not keep legacy iterator patterns if you are writing new TensorFlow 2 code. Modern dataset iteration is much simpler and avoids this entire class of error.

Summary

  • The error means an initializable TensorFlow 1 iterator was used before iterator.initializer was run.
  • Fix it by calling sess.run(iterator.initializer) before fetching from get_next().
  • Reinitialize the iterator when you need a fresh pass through the dataset.
  • In TensorFlow 2, prefer direct iteration over tf.data.Dataset.
  • If you see this error in modern code, check whether old tf.compat.v1 graph patterns are still present.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.