Search⌘ K
AI Features

Functions of enumerate and eval

Explore how to use Python's built-in functions enumerate and eval. Understand how enumerate helps track positions in loops efficiently. Learn how eval executes string expressions, its potential risks, and when it is safe to use in your code.

enumerate

Have we ever needed to loop over a list and also needed to know where in the list we were at? We could add a counter that we increment as we loop, or we could use Python’s built-in enumerate function!

Example of enumerate() with a string

Let’s try it out on a string!

Python 3.5
my_string = 'abcdefg'
for pos, letter in enumerate(my_string):
print (pos, letter)

In this example, we have a 7-letter string. We will notice that in our loop, we wrap the string in a call to enumerate. This returns the position of each item in the ...