Apa itu iterable di python?

Iterable in Python is any object that can be looped over. In order for an iterable to be looped over, an iterable needs to be converted to an iterator using the

# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
7 method. Once created, it is actually the iterator that gets iterated over. This is also what happens internally when you run a for-loop.

Let’s understand iterators and iterables very clearly.

This covers:
1. What exactly is an iterator and iterable?
2. How to tell the difference between iterator and iterble?
3. What exactly happens when you run a for-loop in Python?
4. How to create a class based iterator?

There is a minor difference between an iterable and an iterator. For example, the List is an iterable but not an iterator.

Let’s understand the difference clearly, so you can write python code that is more efficient, and will enable you to see solutions to problems in a way you might not have thought through before.

Many of the python objects that we have seen so far are ‘Iterables’. List, string, tuples etc are iterables.

What is an iterable?

An iterable is basically a Python object that can be looped over. This means, lists, strings, tuples, dicts and every other object that can be looped over is an iterable.

See this for-loop for example.

# items that appear on the RHS of the for-loop is an iterable
for i in [1,2,3,4,5]:
print(i)

Output

1
2
3
4
5

So what really happens when you run a for loop?

An iterable defines an

# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
7 method which returns an iterator. This means, everytime you call the
# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
9 on an iterable, it returns an iterator.

# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
#> list_iterator

The iterator in turn has

#> list_iterator
0 method defined.

So, whenever you use a for-loop in Python, the

#> list_iterator
0 method is called automatically to get each item from the iterator, thus going through the process of iteration.

In a similar way, you can loop over strings, tuples, dictionaries, files, generators (which we will cover next) etc.

How to tell if an object can be looped over or is an iterable?

You can tell whether an object is iterable or not by the presence of the

# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
7 dunder method.

MLPlus Industry Data Scientist Program

Do you want to learn Data Science from experienced Data Scientists?

Build your data science career with a globally recognised, industry-approved qualification. Solve projects with real company data and become a certified Data Scientist in less than 12 months. .

Apa itu iterable di python?

Get Free Complete Python Course

Build your data science career with a globally recognised, industry-approved qualification. Get the mindset, the confidence and the skills that make Data Scientist so valuable.

So, technically speaking, any python object that defines a

# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
7 method, is an iterable. This is a special method, aka, a ‘Dunder method’ or ‘magic method.’

# check the methods of list
L = [1, 2, 3]
print(dir(L))

Output:

#> ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

You can find the

#> list_iterator
4 method in the list above. Likewise, you can find that method in every other iterable.

We are now clear with what an iterable is.

So, what is an iterator?

What is an iterator?

You know that you will get an

#> list_iterator
5 by calling the
# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
9 on an iterable.

Iterator is an iterable that remembers its state. Which means, it’s a python object with a state so it remembers where it is during iteration.

Like how an iterable has a

# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
7 method, which gives an iterator, an iterator defines a
#> list_iterator
0 method that makes the iteration possible.

S = "Roger"
print(type(S))

Output:

#> <class 'str'>;
# Create iterator.
T = S.__iter__()
# or
# T = iter(S)

print(type(T))

Output

#> <class 'str_iterator'>;

We now have an iterator. It must have a state, so the next time it is iterated, it will know how to get the next value.

It does it using the dunder

#> list_iterator
0 method.

So, technically, an iterator is an object that has executed the dunder methods:

#> list_iterator
4 and
# check the methods of list
L = [1, 2, 3]
print(dir(L))
1.

1
2
3
4
5
0

Output

1
2
3
4
5
1
1
2
3
4
5
2

Output

1
2
3
4
5
3

When you call

# check the methods of list
L = [1, 2, 3]
print(dir(L))
2, it is actually calling the dunder method
#> list_iterator
0 in the background.

1
2
3
4
5
4

Output

1
2
3
4
5
5

After it has exhasted all the items, it errors our with

# check the methods of list
L = [1, 2, 3]
print(dir(L))
4 on further calling
#> list_iterator
0.

1
2
3
4
5
6

That means the iterator has been exhausted.

Also notice, the list

# check the methods of list
L = [1, 2, 3]
print(dir(L))
6 also contains the
# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
7 method, which makes it return the same iterable, instead.

Creating your own iterator object

Python allows you to create your own iterator object. All you need to do is to define the

# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
7 and
#> list_iterator
0 methods, along with the constructor (
#> ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
0) ofcourse.

1
2
3
4
5
7

Output:

1
2
3
4
5
8
1
2
3
4
5
9
# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
0
# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
1

Output:

# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
2
# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
3

Practice Exercises on Iterators:

Q1: Make changes to the code so that it returns a list of words in each line.

Q2: Write an iterator class that reverses a string

Solution 2:

# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
4
# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
5

Output:

# Get iterator from iterable
iterator_from_list = iter([1,2,3,4,5])
type(iterator_from_list)
6

Awesome! That’s how you create an iterator on your own.

Now, if this feels cumbersome, you can create and work with Generators.

Selva Prabhakaran

Selva is the Chief Author and Editor of Machine Learning Plus, with 4 Million+ readership. He has authored courses and books with100K+ students, and is the Principal Data Scientist of a global firm.