How does this for loop work on the following string?

Viewed 52

I have been working through Automate the Boring Stuff by Al Sweighart. I'm struggling with understanding the code below:

INPUT

message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}

for character in message:
 count.setdefault(character, 0)
 count[character] = count[character] + 1

print(count)

OUTPUT

{'I': 1, 't': 6, ' ': 13, 'w': 2, 'a': 4, 's': 3, 'b': 1, 'r': 5, 'i': 6, 'g': 2, 'h': 3, 'c': 3, 'o': 2, 'l': 3, 'd': 3, 'y': 1, 'n': 4, 'A': 1, 'p': 1, ',': 1, 'e': 5, 'k': 2, '.': 1}

QUESTION

Since it does not matter what the variable in a for loop is called (ie character can be changed to x, pie etc) how does the code know to run the loop through each character in the string?

3 Answers

It's not about the variable's name, it's about the object this variable points to. The implementation of the loop in the Python virtual machine knows how to iterate over objects based on their types.

Iterating over something is implemented as iterating over iter(something), which in turn is the same as iterating over something.__iter__(). Different classes implement their own versions of __iter__, so that loops work correctly.

str.__iter__ iterates over the individual characters of a string, list.__iter__ - over the list's elements and so on.


You could create your own object and iterate over it:

class MyClass:
    def __iter__(self):
        return iter([1,2,3,4])

my_object = MyClass()
for x in my_object:
    print(x)

This will print the numbers from 1 to 4.

A string is an array in python. So, it means that when you loop on a string, you loop on each character; in your case, you set what has been read to character.

Then, setdefault maps character to 0 if character is not yet in the dict. The rest looks quite straightforward.

Related