Iterables and iterators

INPUT · Slides

Why the same for loop works on everything

01 / 06

The same writing worked on all of them

You have used for on all sorts of things by now: lists, strings, dictionaries, range, files. Every one of them looped the same way.

That is not luck. Python is built for it. This chapter opens up the machinery and looks inside.

for fruit in ["apple", "orange"]:    print(fruit)for letter in "hi":    print(letter)

Result

apple
orange
h
i

02 / 06

A thing you can loop over is an iterable

Anything you can put after for is called an iterable — a thing you can loop over. The word comes from iterate, to go round again.

Everything you have met so far was one.

  • a list
  • a string
  • a dictionary
  • a tuple
  • what range makes
  • an open file

If you can hand it to for, it is an iterable. That is the whole of the word.

scores = {"Yui": 90, "Sou": 60}for name in scores:    print(name)for number in range(2):    print(number)

Result

Yui
Sou
0
1

03 / 06

The iterator hands them out one at a time

An iterable does not hand out the values itself. Ask it, and it builds a fresh "give them out one at a time" helper and passes you that.

That helper is called an iterator. Give an iterable to the function iter and you can see one.

print(iter(["apple", "orange"]))<list_iterator object at 0x1234abcd>

The display looks like an incantation, but all it says is "an iterator for a list". The number on the end is the address it is kept at, and it changes every time you run.

04 / 06

The three things for does behind your back

The inside of for is only three steps.

  • ask the iterable for an iterator
  • ask the iterator for the next value
  • stop when it says there are no more

That is all. So anything that can answer those three goes into a for — a list, a file, or some container built by somebody you have never heard of.

05 / 06

Hand it something you cannot loop over

Turn it round: give for something that has not made that promise and you get an error. A number is one.

not iterable means "this is not a thing you can loop over". Python writes its errors in exactly the words this chapter is teaching you.

for number in 5:    print(number)

Result

TypeError: 'int' object is not iterable

06 / 06

Nothing new, and yet

Honestly, this chapter adds almost nothing to what you can do. It opens up something you could already do and looks inside.

But going through it makes everything after it easier. The documentation for Python is full of the phrase "you can loop over this", and from now on you will know exactly what it means.

Next lesson you do the same job by hand, without a for at all.