CHAPTER 8 · 4 lessons · 52 exercises
Iterables and iterators
Why the same for loop works on a list, a string and a file. You get to see how Python is put together.
You have now used for on all sorts of things: lists, strings, dictionaries, files. Every one of them looped the same way. That is not luck; Python is designed for it.
The machinery has names. A thing you can loop over is an iterable, and the thing that actually hands you one item at a time is an iterator. Behind the scenes for asks the iterable for an iterator, keeps asking it for the next value, and stops when it is told there are no more. That is all.
This chapter does not add anything new that you can do. It opens up something you could already do and looks inside. So it may feel less than practical. But it pays off from here on, because Python's libraries are built on top of this arrangement, and you will be able to read exactly what documentation means when it says "you can loop over this".
Specifically, you will use two functions, iter and next, to redo by hand what for does for you. Write it once and it lands, properly, that for is not magic at all.
On top of that come two things you will use constantly. enumerate hands you the position and the item together: write for i, fruit in enumerate(fruits): and you never have to count by hand again. zip lines two lists up side by side and walks them together, which is what you want when you are matching a list of names against a list of scores.
These two are where beginner code and experienced code look most different. Spot someone incrementing a counter themselves and you can tell they have not met enumerate — that is how ordinary it is in Python.
Lessons in this chapter
How a for loop works
- 80Why the same for loop works on everything
forworks on a list, on a string, on a dictionary. Open it up and see why.Go to the exercises - 81Doing a for loop by handWrite
iterandnextonce and it lands, properly, thatforis no magic at all.Go to the exercises - 82Getting the position and the item togetherStop counting positions yourself.
enumeratehands you the number along with the item.Go to the exercises - 83Walking two rows togetherA list of names and a list of scores.
ziplines them up and matches them off.Go to the exercises