Iterable Types in Python

An iterable object in Python object that can have none, one, or several elements. An iterable is capable of returning its elements as needed by the user.

Due to this capability, we can use a Python for loop to iterate through an iterable.

In reality, the range() method is iterable since its output may be iterated over:

Code

Output

0
1
2
3
4

A string in Python is also an iterable object since we can iterate over its elements using a for loop:

Code

Output

P
y
t
h
o
n

Iterables include lists, tuples, and dictionaries since they can be looped over. As an example:

Code

Output

Elements of the list [1, 2, 3, 4, 5, 6]: 
1
2
3
4
5
6
Elements of the tuple (1, 2, 3, 4, 5, 6): 
1
2
3
4
5
6
Elements of the dictionary {'a': 1, 'b': 2, 'c': 3}: 
a 1
b 2
c 3

The general rule is that it's iterable if one can loop over anything.

What is an Iterator?

It is possible to iterate over an iterable only. And the component that conducts the iteration is known as an iterator.

The iter() method obtains an iterable from the given iterable. As an example:

Code

Output

<list_iterator object at 0x7f56952b54f0>
The type of iter_list object is:  <class 'list_iterator'>

Once we have the iterator object, we can use the next() method to retrieve the next item from the iterable:

Code

Output

<list_iterator object at 0x7f56952b5b50>
1

The next() method gives the next item in the iterable each time it is used. As an example:

Code

Output

<list_iterator object at 0x7f56951d6c40>
1
2
3
4
5

If there isn't any more element and we call the next() function, we'll get an exception.

Code

Output

<list_iterator object at 0x7f56952b7100>
1
2
3
4
5
6
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-14-4456e4ae5daa> in <module>
     11 
     12 for i in range(7):
---> 13   e = next(list_iter)
     14   print(e)
     15 

StopIteration: 

The iterator is a state operator. It indicates that it is no longer available after we take an item from a particular iterator.

In other words, it becomes empty after we loop over the given iterator. It will return nothing if we iterate over it further.

Because an iterator may be iterated over, it is also considered an iterable object in Python. This is quite perplexing. As an example:

Code

Output

1
2
3
4
5
6

If we call the iter() method and provide it an iterable, it will return an iterator of the same iterator.

Hence, we have learned quite a few things about iterables in Python.


Next TopicPython JWT




Latest Courses