Open In App

Python | Difference between iterable and iterator

Last Updated : 27 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Iterable is an object, that one can iterate over. It generates an Iterator when passed to iter() method. An iterator is an object, which is used to iterate over an iterable object using the __next__() method. Iterators have the __next__() method, which returns the next item of the object.

Note: Every iterator is also an iterable, but not every iterable is an iterator in Python.

For example, a list is iterable but a list is not an iterator. An iterator can be created from an iterable by using the function iter(). To make this possible, the class of an object needs either a method __iter__, which returns an iterator, or a __getitem__ method with sequential indexes starting with 0. 

Example 1: 

We know that str is iterable but it is not an iterator. where if we run this in for loop to print string then it is possible because when for loop executes it converts into an iterator to execute the code.

Python3




# code
next("GFG")


Output :

Traceback (most recent call last):
  File "/home/1c9622166e9c268c0d67cd9ba2177142.py", line 2, in <module>
    next("GFG")
TypeError: 'str' object is not an iterator

Here iter( ) is converting s which is a string (iterable) into an iterator and prints G for the first time we can call multiple times to iterate over strings.

When a for loop is executed, for statement calls iter() on the object, which it is supposed to loop over. 
If this call is successful, the iter call will return an iterator object that defines the method __next__(), which accesses elements of the object one at a time.                                                                                                                                          

Python3




# code
s="GFG"
s=iter(s)
print(s)
print(next(s))
print(next(s))
print(next(s))


Output:

<str_iterator object at 0x7f822a9c3210>
G
F
G

The __next__() method will raise a StopIteration exception if there are no further elements available. 
The for loop will terminate as soon as it catches a StopIteration exception.   
Let’s call the __next__() method using the next() built-in function. 

Example 2:

Function ‘iterable’ will return True if the object ‘obj’ is an iterable and False otherwise. 

Python3




# list of cities
cities = ["Berlin", "Vienna", "Zurich"]
 
# initialize the object
iterator_obj = iter(cities)
 
print(next(iterator_obj))
print(next(iterator_obj))
print(next(iterator_obj))


Output:

Berlin
Vienna
Zurich

Note: If ‘next(iterator_obj)’ is called one more time, it would return ‘StopIteration’.   

Example3:

Check object is iterable or not.

Python3




# Function to check object
# is iterable or not
def it(ob):
  try:
      iter(ob)
      return True
  except TypeError:
      return False
 
# Driver Code
for i in [34, [4, 5], (4, 5),
{"a":4}, "dfsdf", 4.5]:
 
    print(i,"is iterable :",it(i))


Output:

34 is iterable : False
[4, 5] is iterable : True
(4, 5) is iterable : True
{'a': 4} is iterable : True
dfsdf is iterable : True
4.5 is iterable : False


Previous Article
Next Article

Similar Reads

Python | Consuming an Iterable and Diagnosing faults in C
The article aims to write C extension code that consumes items from any iterable object such as a list, tuple, file, or generator. Code #1 : C extension function that shows how to consume the items on an iterable. static PyObject* py_consume_iterable( PyObject* self, PyObject* args) { PyObject* obj; PyObject* iter; PyObject* item; if (!PyArg_ParseT
2 min read
How to check if an object is iterable in Python?
In simple words, any object that could be looped over is iterable. For instance, a list object is iterable and so is an str object. The list numbers and string names are iterables because we are able to loop over them (using a for-loop in this case). In this article, we are going to see how to check if an object is iterable in Python. Examples: Inp
3 min read
How to Fix TypeError: 'NoneType' object is not iterable in Python
Python is a popular and versatile programming language, but like any other language, it can throw errors that can be frustrating to debug. One of the common errors that developers encounter is the "TypeError: 'NoneType' object is not iterable." In this article, we will explore various scenarios where this error can occur and provide practical solut
8 min read
Cannot Unpack Non-iterable Nonetype Objects in Python
The "Cannot Unpack Non-iterable NoneType Objects" error is a common issue in Python that occurs when attempting to unpack values from an object that is either None or not iterable. This error often arises due to incorrect variable assignments, function returns, or unexpected results from external sources. In this article, we will explore some code
3 min read
Difference Between Iterator VS Generator
A process that is repeated more than one time by applying the same logic is called an Iteration. In programming languages like python, a loop is created with few conditions to perform iteration till it exceeds the limit. If the loop is executed 6 times continuously, then we could say the particular block has iterated 6 times. Example: [GFGTABS] Pyt
3 min read
Python __iter__() and __next__() | Converting an object into an iterator
In many instances, we get a need to access an object like an iterator. One way is to form a generator loop but that extends the task and time taken by the programmer. Python eases this task by providing a built-in method __iter__() for this task. In this article, we will see about Python __iter__() and __next__(). Python __iter__()The __iter__() fu
4 min read
Python | range() does not return an iterator
range() : Python range function generates a list of numbers which are generally used in many situation for iteration as in for loop or in many other cases. In python range objects are not iterators. range is a class of a list of immutable objects. The iteration behavior of range is similar to iteration behavior of list in list and range we can not
2 min read
Python PIL | ImageSequence.Iterator()
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageSequence module contains a wrapper class that lets you iterate over the frames of an image sequence. ImageSequence.Iterator() This class implements an iterator object that can be used to loop over an image sequence. You can use the [ ]
1 min read
Iterator Method - Python Design Patterns
Iterator method is a Behavioral Design Pattern that allows us to traverse the elements of the collections without taking the exposure of in-depth details of the elements. It provides a way to access the elements of complex data structure sequentially without repeating them.According to GangOfFour, Iterator Pattern is used " to access the elements o
4 min read
Ways to increment Iterator from inside the For loop in Python
For loops, in general, are used for sequential traversal. It falls under the category of definite iteration. Definite iterations mean the number of repetitions is specified explicitly in advance. But have you ever wondered, what happens, if you try to increment the value of the iterator from inside the for loop. Let's see with the help of the below
2 min read
Article Tags :
Practice Tags :