Since we spent the last few posts discussing iterators, it is time to introduce enumerate and range. Both enumerate and range are what are known as iterators. An iterator is defined as:
An iterator is an object that contains a countable number of values that can be traversed through
Source: https://www.w3schools.com/python/python_iterators.asp
enumerate()
It’s time for a new method introduction! This method is called enumerate(). With enumerate, you can have an automatic counter when you loop over an iterator. The easiest way to visualize it is with a list and a string. Enumerate will associate the index with the object you are at in the for-loop. If we had a list of fruit and we wanted to add all the fruit at an even index to a new list:
new_lst = []
my_lst = ['orange','pear','apple','grape','banana','kiwi','dragonfruit','strawberries']
for idx,obj in enumerate(my_lst):
if idx % 2 == 0:
new_lst.append(obj)
new_lst
['orange', 'apple', 'banana', 'dragonfruit']
range()
Another method we can introduce for loops is range(). Range is a Python generator. Generators are iterators, but you can only iterate over them once. This is because they do not store information in memory. As you request data from a generator, it will generate the values on the fly. It is good to know that you do not need to do anything with what you are iterating over for the for-loop. Your iterator can strictly counter how often you want the for loop to run. Typically, it can be done with anything as long as it is not called in the for loop, but the best practice is to make it an underscore. _. Back to our chores list, what if we wanted to pop items off of the list and,when the list is empty, print something:
my_chorelist = ['walking dogs', 'emptying dishwasher', 'taking out trash', 'mowing lawn', 'getting gas', 'cleaning cars]
for in range(len(my_chore_list)):
completed_chore = my_chore_list.pop()
print(f"I am done with chore: {completed_chore}")
if len(my_chore_list) == 0:
print('Ah, finally time to relax and read that Python blog post over on blog.mikelossmann.me!')
When the loop is executed, the following will be displayed:
I am done with chore: cleaning cars I am done with chore: getting gas I am done with chore: mowing lawn I am done with chore: taking out trash I am done with chore: emptying dishwasher I am done with chore: walking dogs Ah, finally time to relax and read that Python blog post over on routedinterface.com!
For loops are incredibly versatile and powerful. For loops can work with conditionals and what we will talk about next, while loops.