Teaching Kids Programming – Re-implement the enumerate in Python using yield in a Generator


Teaching Kids Programming: Videos on Data Structures and Algorithms

The enumerate is a basic Python function (a generator) that is commonly used in a for loop to simplify your code and express it in a Pythonic manner. See below example:

1
2
3
s = "Hello!"
for i, v in enumerate(list(s)):
    print(i, v)
s = "Hello!"
for i, v in enumerate(list(s)):
    print(i, v)

And you will get:

0 H
1 e
2 l
3 l
4 o
5 !

It is equivalent to the following, but nicer:

1
2
3
s = "Hello!"
for i in range(len(s)):
    print(i, s[i])
s = "Hello!"
for i in range(len(s)):
    print(i, s[i])

Implement the enumerate generator in Python

To implement this, it is actually quite easy, we just have to yield a tuple with index, and value in a for loop, see below:

1
2
3
def my_enumerate(a):
    for i in range(len(a)):
        yield (i, a[i])
def my_enumerate(a):
    for i in range(len(a)):
        yield (i, a[i])

And you can use it virtually the same way:

1
2
for i, v in my_enumerate(list(s)):
    print(i, v)
for i, v in my_enumerate(list(s)):
    print(i, v)

Prints the following:

0 H
1 e
2 l
3 l
4 o
5 !

I hope now you have a taste on how the “yield”, and generator, and also the enumerate function in Python works!

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
303 words
Last Post: Teaching Kids Programming - Introduction and Re-implement the zip and zip_longest Function in Python
Next Post: Number Of Rectangles That Can Form The Largest Square

The Permanent URL is: Teaching Kids Programming – Re-implement the enumerate in Python using yield in a Generator

Leave a Reply