Iterable in Python

Iterable

An iterable is any Python object capable of returning its members one at a time, permitting it to be iterated over in a for-loop, such as lists, tuples, sets and strings – as well as generators. An iterable object implements the __getitem__ and __len__ methods.

An object can also implement the __iter__ method to return an iterator.

Iterator

An iterator is any object in Python which has a __next__ method defined.

Consider a string, it is iterable, but it’s not an iterator. To iterate over it, we need to call the iter() function to return an iterator object from an iterable:

name = "fred"

for ch in iter(name):
    print(ch)

# outputs:

f
r
e
d

Here is an example of an iterable object:

class Members:
    def __init__(self, members=None):
        self._members = members or []

    def __getitem__(self, index):
        return self._members[index]

    def __len__(self):
        return len(self._members)


book_club = Members(['Fred', 'Tom', 'Alice', 'Betty', 'Mike'])

# create an iterator for our object
for member in iter(book_club):
    print(member)

# create a list from our object
print(list(book_club))

# outputs:

Fred
Tom
Alice
Betty
Mike

['Fred', 'Tom', 'Alice', 'Betty', 'Mike']

In this second example, we return an iterator directly:

class Skills:
    def __init__(self, skills=None):
        self._skills = skills or []

    def __iter__(self):
        return iter(self._skills)


personal_skills = Skills(['C#', 'Delphi'])

for skill in personal_skills:
    print(skill)

# outputs:

C#
Delphi

This example demonstrates that a generator can be iterated over directly:

friends = (name for name in ['john', 'peter', 'mary', 'michael'])

for friend in friends:
    print(friend)

# outputs:

john
peter
mary
michael

Lastly, here is a very neat recipe from the Python Cookbook, it allows you to iterate over a collection of fixed sized records or chunks:

from functools import partial

RECORD_SIZE = 32

with open('somefile.data', 'rb') as f:
    records = iter(partial(f.read, RECORD_SIZE), b'')
    for r in records:
        ...

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s