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:
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:
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:
def my_enumerate(a):
for i in range(len(a)):
yield (i, a[i])
And you can use it virtually the same way:
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) —
286 wordsLast 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