Iterators are functions that call values of a data structure in a sequence one after another and Iterables are objects which can be looped over by using an iterator. In this article, I will take you through what are Iterables and Iterators in the Python programming language.
Iterables and Iterators in Python
In the Python programming language, Iterables are objects which can be iterated. Iteration means to loop over something or selecting all elements in a data structure one by one. In simple terms, when we loop over an array of values then the process of looping over an array is known as iteration and here array is an object which is iterable.
All the data structures or any file which can be iterated are known as iterables in Python. For example, lists, dictionaries, tuples, files, etc. are iterables in python. So when we loop over an object then that object is known as iterable. Below is a simple example:
a = [10, 20, 30] for i in a: print(i)
10 20 30
I the above code, I have first created a list of values then I am using a for loop on the list which makes this list iterable.
Now, what are iterators? In the above section, I mentioned that any object which can be looped over are iterables. When we use a function to iterate over an iterable object then those functions are nothing but iterators. We have some built-in functions in Python like “iter” and “next”, we can use these functions to iterate over and object to get one element at one time.
Let’s have a look at how iterators work by understanding the code below:
a = iter([10, 20, 30]) print(next(a)) print(next(a)) print(next(a))
10 20 30
First, I created a Python list inside the iter function. Then I am using the next function to get the first element from the list and so on. These functions are iterators in python but we generally use for and while loop statements to iterate over iterables as for and while are built upon iterators.
Also, Read – Python Projects with Source Code: Solved and Explained.
I hope you now have understood what is the difference between iterables and iterators in the Python programming language. Iterables are objects which can be looped over and iterators and functions that call values in a sequence one by one. I hope you liked this article on what are Iterables and Iterators in Python. Feel free to ask your valuable questions in the comments section below.