🌐
W3Schools
w3schools.com › python › python_iterators.asp
Python Iterators
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().
🌐
Real Python
realpython.com › python-for-loop
Python for Loops: The Pythonic Way – Real Python
July 17, 2026 - Python’s for loop allows you to iterate over the items in a collection, such as lists, tuples, strings, and dictionaries. The for loop syntax declares a loop variable that takes each item from the collection in each iteration. This loop is ideal for repeatedly executing a block of code on each item in the collection.
🌐
GeeksforGeeks
geeksforgeeks.org › python › iterate-over-a-list-in-python
Iterate Over a List in Python - GeeksforGeeks
Given a list, the task is to iterate over all its elements.
Published: July 16, 2026
🌐
Programiz
programiz.com › python-programming › iterator
Python Iterators (With Examples)
Using an iterator method, we can loop through an object and return its elements. Technically, a Python iterator object must implement two special methods, __iter__() and __next__(), collectively called the iterator protocol.
🌐
Mimo
mimo.org › glossary › python › iterator
Python Iterator: Syntax, Usage, and Examples
Iterators enable memory-efficient looping by fetching elements one at a time rather than loading an entire sequence into memory. A Python iterator is an object that produces the next item in a sequence each time you call next() on it. You get an iterator by calling the built-in iter() function ...
🌐
Python
docs.python.org › 3 › library › itertools.html
itertools — Functions creating iterators for efficient looping
This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python. The module standardizes a core set...
🌐
W3Schools
w3schools.com › python › python_for_loops.asp
Python For Loops
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... A for loop is used for iterating over a sequence (that ...
🌐
Real Python
realpython.com › python-iterators-iterables
Iterators and Iterables in Python: Run Efficient Iterations – Real Python
June 10, 2026 - When you use a while or for loop to repeat a piece of code several times, you’re actually running an iteration. That’s the name given to the process itself. In Python, if your iteration process requires going through the values or items ...
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › eli5: what exactly is an iteration and with an example.
r/learnpython on Reddit: ELI5: What exactly is an iteration and with an example.
August 15, 2022 -

I'm hearing this word constantly, but I just vaguely understand it.

Also when should I use while and when the for loop?

Top answer
1 of 4
6
An iterator is an object that contains a countable number of values. An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods iter() and next(). Ref: https://www.w3schools.com/python/python_iterators.asp An iterator is basically something you can loop over/through and objects being iterable depends on their class having a __iter__ method. For example: On a list you will iterate through all items in the list foo = ["b", "a", "r"] for i in foo: print(i) b a r On a string you will iterate through all individual characters that make up that string foo = "bar" for i in foo: print(i) b a r
2 of 4
3
I guess iteration could also be described as traversal. You have a collection of objects, let's say a collection of cars. When you traverse or rather when you iterate through the collection, you simply inspect one object at a time and are given the opportunity to affect this object somehow. You do this for every object in the collection. When should you use a for and a while loop? Generally, in Python you use a for loop when you want to iterate over a collection, or over a range. So, you roughly know how many times you need to iterate. Pythons for loop is more similar to ForEach loops of other languages. You use a while loop if you would like to loop the code, based on a condition, rather than range, or the length of a collection. For example if variable x is 5, with a while loop you can loop over and over, you don't need to know how many times, until say 5 becomes 0. If the condition of 5 being 0 is satisfied, the loop stops.
🌐
W3Schools
w3schools.com › python › python_lists_loop.asp
Python - Loop Lists
Learn more about for loops in our Python For Loops Chapter. You can also loop through the list items by referring to their index number. Use the range() and len() functions to create a suitable iterable.
🌐
Python for Everybody
py4e.com › html3 › 05-iterations
Iterations (Python for Everybody)
We call the while statement an indefinite loop because it simply loops until some condition becomes False, whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set. The syntax of a for loop is similar to the while loop in that there is a for statement and a loop body: friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends: print('Happy New Year:', friend) print('Done!') In Python terms, the variable friends is a list1 of three strings and the for loop goes through the list and executes the body once for each of the three strings in the list resulting in this output:
🌐
GeeksforGeeks
geeksforgeeks.org › python › iterators-in-python
Iterators in Python - GeeksforGeeks
An iterator in Python is an object used to traverse through all the elements of a collection (like lists, tuples or dictionaries) one element at a time.
Published: June 5, 2026
🌐
Kinsta®
kinsta.com › home › resource center › blog › python › iterate like a pro: a guide to python iterables
Iterate Like a Pro: A Guide to Python Iterables - Kinsta®
November 22, 2023 - It also explains how to implement custom iterable types and perform advanced operations. In Python, you can iterate through diverse iterable types using a for loop.
🌐
LearnPython.com
learnpython.com › blog › python-list-loop
7 Ways to Loop Through a List in Python | LearnPython.com
This track will help you understand the fundamentals of programming, including lists and iteration. Without further delay, let's dive right in! Using a Python for loop is one of the simplest methods for iterating over a list or any other sequence ...
🌐
Medium
medium.com › @AlexanderObregon › how-pythons-iterators-and-iterables-work-e1ace2d3a494
How Python’s Iterators and Iterables Work | Medium
January 2, 2025 - While all iterators are iterables, not all iterables are iterators. An iterable must implement the __iter__ method, which returns an iterator. Iterators, by definition, implement both __iter__ and __next__. This relationship allows Python’s iteration protocol to work seamlessly across various object types.
🌐
GeeksforGeeks
geeksforgeeks.org › python › iterate-over-a-set-in-python
Iterate over a set in Python - GeeksforGeeks
July 11, 2025 - Explanation: iter(a) function returns an iterator for the set and the for loop prints each character in an unordered sequence, which may vary each time. enumerate() is a built-in Python function that adds a counter (index) to an iterable.
Top answer
1 of 6
57

Your suspicion is correct: the iterator has been consumed.

In actuality, your iterator is a generator, which is an object which has the ability to be iterated through only once.

type((i for i in range(5))) # says it's type generator 

def another_generator():
    yield 1 # the yield expression makes it a generator, not a function

type(another_generator()) # also a generator

The reason they are efficient has nothing to do with telling you what is next "by reference." They are efficient because they only generate the next item upon request; all of the items are not generated at once. In fact, you can have an infinite generator:

def my_gen():
    while True:
        yield 1 # again: yield means it is a generator, not a function

for _ in my_gen(): print(_) # hit ctl+c to stop this infinite loop!

Some other corrections to help improve your understanding:

  • The generator is not a pointer, and does not behave like a pointer as you might be familiar with in other languages.
  • One of the differences from other languages: as said above, each result of the generator is generated on the fly. The next result is not produced until it is requested.
  • The keyword combination for in accepts an iterable object as its second argument.
  • The iterable object can be a generator, as in your example case, but it can also be any other iterable object, such as a list, or dict, or a str object (string), or a user-defined type that provides the required functionality.
  • The iter function is applied to the object to get an iterator (by the way: don't use iter as a variable name in Python, as you have done - it is one of the keywords). Actually, to be more precise, the object's __iter__ method is called (which is, for the most part, all the iter function does anyway; __iter__ is one of Python's so-called "magic methods").
  • If the call to __iter__ is successful, the function next() is applied to the iterable object over and over again, in a loop, and the first variable supplied to for in is assigned to the result of the next() function. (Remember: the iterable object could be a generator, or a container object's iterator, or any other iterable object.) Actually, to be more precise: it calls the iterator object's __next__ method, which is another "magic method".
  • The for loop ends when next() raises the StopIteration exception (which usually happens when the iterable does not have another object to yield when next() is called).

You can "manually" implement a for loop in python this way (probably not perfect, but close enough):

try:
    temp = iterable.__iter__()
except AttributeError():
    raise TypeError("'{}' object is not iterable".format(type(iterable).__name__))
else:
    while True:
        try:
            _ = temp.__next__()
        except StopIteration:
            break
        except AttributeError:
            raise TypeError("iter() returned non-iterator of type '{}'".format(type(temp).__name__))
        # this is the "body" of the for loop
        continue

There is pretty much no difference between the above and your example code.

Actually, the more interesting part of a for loop is not the for, but the in. Using in by itself produces a different effect than for in, but it is very useful to understand what in does with its arguments, since for in implements very similar behavior.

  • When used by itself, the in keyword first calls the object's __contains__ method, which is yet another "magic method" (note that this step is skipped when using for in). Using in by itself on a container, you can do things like this:

    1 in [1, 2, 3] # True
    'He' in 'Hello' # True
    3 in range(10) # True
    'eH' in 'Hello'[::-1] # True
    
  • If the iterable object is NOT a container (i.e. it doesn't have a __contains__ method), in next tries to call the object's __iter__ method. As was said previously: the __iter__ method returns what is known in Python as an iterator. Basically, an iterator is an object that you can use the built-in generic function next() on1. A generator is just one type of iterator.

  • If the call to __iter__ is successful, the in keyword applies the function next() to the iterable object over and over again. (Remember: the iterable object could be a generator, or a container object's iterator, or any other iterable object.) Actually, to be more precise: it calls the iterator object's __next__ method).
  • If the object doesn't have a __iter__ method to return an iterator, in then falls back on the old-style iteration protocol using the object's __getitem__ method2.
  • If all of the above attempts fail, you'll get a TypeError exception.

If you wish to create your own object type to iterate over (i.e, you can use for in, or just in, on it), it's useful to know about the yield keyword, which is used in generators (as mentioned above).

class MyIterable():
    def __iter__(self):
        yield 1

m = MyIterable()
for _ in m: print(_) # 1
1 in m # True    

The presence of yield turns a function or method into a generator instead of a regular function/method. You don't need the __next__ method if you use a generator (it brings __next__ along with it automatically).

If you wish to create your own container object type (i.e, you can use in on it by itself, but NOT for in), you just need the __contains__ method.

class MyUselessContainer():
    def __contains__(self, obj):
        return True

m = MyUselessContainer()
1 in m # True
'Foo' in m # True
TypeError in m # True
None in m # True

1 Note that, to be an iterator, an object must implement the iterator protocol. This only means that both the __next__ and __iter__ methods must be correctly implemented (generators come with this functionality "for free", so you don't need to worry about it when using them). Also note that the ___next__ method is actually next (no underscores) in Python 2.

2 See this answer for the different ways to create iterable classes.

2 of 6
20

For loop basically calls the next method of an object that is applied to (__next__ in Python 3).

You can simulate this simply by doing:

iter = (i for i in range(5))

print(next(iter))
print(next(iter))  
print(next(iter))  
print(next(iter))  
print(next(iter)) 

# this prints 1 2 3 4 

At this point there is no next element in the input object. So doing this:

print(next(iter))  

Will result in StopIteration exception thrown. At this point for will stop. And iterator can be any object which will respond to the next() function and throws the exception when there are no more elements. It does not have to be any pointer or reference (there are no such things in python anyway in C/C++ sense), linked list, etc.

🌐
AskPython
askpython.com › python › list › iterate-through-list-in-python
Ways to Iterate Through List in Python - AskPython
January 16, 2024 - In the above snippet of code, the list is iterated using range() function which traverses through 0(zero) to the length of the list defined. ... Python for loop can be used to iterate through the list directly.
🌐
Python
wiki.python.org › moin › Iterator
Iterator - Python Wiki
An iterator object implements __next__, which is expected to return the next element of the iterable object that returned it, and to raise a StopIteration exception when no more elements are available.
🌐
Python
docs.python.org › 3 › c-api › iterator.html
Iterator Objects — Python 3.14.7 documentation
Python provides two general-purpose iterator objects. The first, a sequence iterator, works with an arbitrary sequence supporting the__getitem__() method. The second works with a callable object an...