Before we jump into the understanding of enumerate function in Python programming language, let us unfold the chapter by finding out what enumerate is, what it means to enumerate something. The term enumerate is commonly used in mathematics and computer science. Well, enumerating is nothing but ordered listing of all the elements in a collection.
Now that we have an idea about what enumerate in general means, we can go ahead and start working on the enumerate function. Following is the list of all the topics that we will cover in this module, in case you need to jump to a specific one.
As mentioned earlier in order to perform enumerate Python programming language offers a simple function which not only makes iterating operations a lot easier but also helps our program look cleaner.
Let me give you prove this to you with the help of an example.
But the same thing can be achieved by one simple function without using range and length function, which can become tricky at times.
Let us see how enumerate makes it less complicated.
With the help of Python enumerate function we can iterate over the index and value in a Python list by using a basic for loop. Let us see how.
Which gives the same output:
Even though both the program has same length, you can tell just by looking that the second one with enumerate function is less complicated. One function is doing all the magic.
Fun fact: With the help of enumerate we can create a dictionary out of a list very easily. Let us see how:
Just the way we performed enumerate in a list, we can do the same in a tuple. Let us try out one simple example.
Now that we have learnt how to enumerate a list and how to enumerate a tuple, let us see how to enumerate a list of tuples.
This method of getting values out of tuple is also referred to as tuple unpacking.
Alright, let us move ahead and see how to apply enumerate over a string.
Alright, as you might have noticed the enumerate by default starts from index 0, which is considered as the starting index. Now, with the help of enumerate function in Python, we can also specify the index that we want to operate the enumerate function from.
Let us view how to enumerate from a specific index not from index 0 with the help of an example.
This often comes in handy when you don’t want to start the iteration from 0.
Using Python enumerate inside a list comprehension makes things very less complicated for programmer.
Now that we have learned how to use Python enumerate function in our programs in order to make the code less complicated go ahead to the next module learn another very interesting concept, Python Queue. See you there.Previous Next
Download Interview Questions asked by top MNCs in 2019?