Enumerate Function in Python

Free Video Tutorial and Guide

In this video, we're going to look at how to use the Enumerate Function in Python

Video Transcription

Hi, my name is Art and I teach Python at Noble Desktop. In this video, I'm going to show you how to use the built-in function enumerate. I've already Googled it, so here you'll find a link to the Python documentation.

Python for Data Science Bootcamp: Live & Hands-on, In NYC or Online, Learn From Experts, Free Retake, Small Class Sizes,  1-on-1 Bonus Training. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

If it's too technical, there are a bunch of other sources like W3schools and Programmers. Python comes with 67-68 built-in functions and the one we're about to use is enumerate. Let me show you how it works.

So here I have a word and in my previous video I was using the range function to generate an index for this word, "Apple". This time, we will use the enumerate function. We have a couple of options. We could go to the Python documentation or use 'help' right in our environment.

In this case, we are using a Jupiter notebook. You see that it returns an enumerate object. What does this mean? Let's give it a try.

So here, I could pass the word and it returns an object. When you see something like this, don't freak out. What it says is that it did the job and now you have an object hidden somewhere in the Python memory.

There are a couple of options on how to deal with that. We could unpack it and use list unpacking. Another way is to unpack it as a tuple. We could also use a for loop to unpack it.

So, what enumerate does is it returns tuples. Each tuple contains two items. First, we get the index and then the character. Now, what we could do here is, since each tuple contains two items, we could provide two values. We could call this index and item. Now, it looks much cleaner and we could print them. Now, you can see that I'm getting the same result.

Since each tuple contains two items, we could unpack them. That's the idea behind enumerate. It's an alternative to the range function. But here, you could also generate an index and get the character. Now, keep in mind that a string like "Apple" is a sequence of characters. Another sequence data type could be a list.

So, here I have a list with 100, 200, 300, 400, and 500. Now, if I run this on a list, it would work exactly the same. That's how versatile the function is. We are seeing the index and item from the list. Enumerate is a built-in solution in Python to generate an index of each item or character in any sequential data type or container. In my next video, I'm going to show you how to use the zip function.

How to Learn Python

Master Python with hands-on training. Python is a popular object-oriented programming language used for data science, machine learning, and web development. 

Yelp Facebook LinkedIn YouTube Twitter Instagram