After, the list lets learn about the intriguing enumerate function in python. Python is the favorite programming language of many developers; contrary to popular belief, it isn’t merely a “technology for newbies” its power and functionality make it an excellent tool for a plethora of tasks. Python is renowned for its collection of libraries, modules, and functions that it comes packaged with and enumerate() is something we should learn in detail.
So, what is enumerate function?
Python's enumerate function is tool that allows us to create a counter alongside values we're iterating over: as part of a loop, for example.
Enumerate takes an iterable type as its first positional argument, such as a list, and returns an enumerate object containing a number of tuples: one for each item in the iterable. Each tuple contains an integer counter, and a value from the iterable.
If we ever have to iterate through a list while keeping track of the index of each element, enumerate will come in handy.
Let’s see through an example:
words = ['all', 'your', 'base']
for idx, word in enumerate(words):
print(idx, word)
print(list(enumerate(words)))# Output:
# 0 all
# 1 your
# 2 base
# [(0, 'all'), (1, 'your'), (2, 'base')]
Enumerate returns an iterator object instead of a list. The iterator serves to save memory, especially when your input list is large.
So, this is how enumerate function comes handy when we need to keep the count of iteration when dealing with lot of iterations.
You can learn more about this enumerate from here:
Very informative!
ReplyDeleteKnowledgable
ReplyDeleteNice work.....great read
ReplyDeleteGood work
ReplyDelete