Python | Difference between iterable and iterator
Last Updated :
27 Sep, 2022
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
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
Similar Reads
Python Lists In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Python Tuples A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
6 min read
Python Sets Python set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can change.Creating a Set in PythonIn Python, the most basic and efficient method for creating
10 min read
Dictionaries in Python Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
5 min read
Python Arrays Lists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences:Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
9 min read
Python If Else Statements - Conditional Statements In Python, If-Else is a fundamental conditional statement used for decision-making in programming. If...Else statement allows to execution of specific blocks of code depending on the condition is True or False.if Statementif statement is the most simple decision-making statement. If the condition ev
4 min read
Loops in Python - For, While and Nested Loops Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). Additionally, Nested Loops allow looping within loops for more complex tasks. While all the ways provide similar basic functionality, they differ in th
9 min read
Loops and Control Statements (continue, break and pass) in Python Python supports two types of loops: for loops and while loops. Alongside these loops, Python provides control statements like continue, break, and pass to manage the flow of the loops efficiently. This article will explore these concepts in detail.Table of Contentfor Loopswhile LoopsControl Statemen
2 min read
range() vs xrange() in Python The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python3, there is no xrange, but the range function behaves like xrange in Python2. If you want to write code that will run on both Python2 and Python3, you should use range(
4 min read
Using Else Conditional Statement With For loop in Python Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while
2 min read