Skip to Content
Clean Code in Python
book

Clean Code in Python

by Mariano Anaya
August 2018
Intermediate to advanced
332 pages
9h 12m
English
Packt Publishing
Content preview from Clean Code in Python

Sequence objects as iterables

As we have just seen, if an object implements the __iter__() magic method, it means it can be used in a for loop. While this is a great feature, it's not the only possible form of iteration we can achieve. When we write a for loop, Python will try to see if the object we're using implements __iter__, and, if it does, it will use that to construct the iteration, but if it doesn't, there are fallback options.

If the object happens to be a sequence (meaning that it implements __getitem__() and __len__() magic methods), it can also be iterated. If that is the case, the interpreter will then provide values in sequence, until the IndexError exception is raised, which, analogous to the aforementioned StopIteration ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Clean Code in Python - Second Edition

Clean Code in Python - Second Edition

Mariano Anaya
Python for Programmers

Python for Programmers

Paul Deitel, Harvey Deitel

Publisher Resources

ISBN: 9781788835831Supplemental Content