LearnPython.com
  • Courses
  • Articles
  • Log in
  • Create free account
  • fullName

    User profile menu open Open user profile menu avatar
    avatar
    fullName
    Dashboard
    My Profile
    Payment & Billing
    Log out
MENU CLOSE
  • Courses
  • Articles
  • Dashboard
  • My Profile
  • Payment & Billing
  • Log in
  • Create free account
  • Log out 
Back to articles list Articles
24th Oct 2022 5 minutes read

The enumerate() Function in Python

Author's photo
Luke Hande
  • python
  • enumerate
See More

What is the enumerate() function in Python and when do you need it? Find out in this article.

While iterating through a list in Python, you’ll often need to keep track of the list elements’ indexes. The enumerate() function provides a useful way to do this. In this article, we’ll show you how to use this function to take your loops to the next level.

This article is aimed at people without much Python programming experience. If you’re new to programming and want to up your Python game, a good place to start is our Python Basics track. It includes over 100 interactive exercises to get you on your feet.

Python’s enumerate() Function

Before we get started, we should cover some background on the enumerate() function. The syntax looks like this:

enumerate(iterable, start=0)

It takes a required iterable like a list, array, or tuple. There’s also an optional argument that defines the start value of the index counter, which defaults to zero.

Looping with a for loop

Looping in Python is pretty fundamental, and we’ve previously discussed it in a few places. For some background reading, take a look at How to Write a For Loop in Python. And our article on the 7 Ways to Loop Through a List in Python is a good summary of the methods we’ll use here.

Say we have a list of words we want to print out. We can use a for loop to iterate over the elements and use the print() statement to print them to the screen:

>>> words = ['here', 'are', 'some', 'words']
>>> for word in words:
... 	print(word)

Result:

here
are
some
words

Notice that the elements are of the string type. You can check by using the type() built-in function.

We’re taking advantage of a lot of built-in functions in this article, so if you want some relevant learning material, check out our Built-in Algorithms in Python course. Alternatively, we could print out the index of each element of the list by using the range() and len() functions:

>>> for i in range(len(words)):
... 	print(i)

Result:

0
1
2
3

Here, the type of the indices is an integer. But there are some situations where you would want to print both the element and the index in the same loop. One way is to create a counter and increase the counter after each iteration:

>>> i = 0
>>> for word in words:
... 	print(i, word)
... 	i+=1

Result:

0 here
1 are
2 some
3 words

We’re using the addition assignment operator (+=) to increase the counter after each iteration. This gets the job done, but it’s not the most efficient way.

Looping with enumerate()

This is where the enumerate() function comes in to make our lives easier. Instead of creating a counter and iterating over the elements, we can get the same result more efficiently using enumerate():

>>> for i, word in enumerate(words):
... 	print(i, word)

Result:

0 here
1 are
2 some
3 words

The indices start from the default value of zero and are printed as integers.  The words are printed as strings.

Let’s step up the complexity by considering the following use case. We have the results from a 100m running race, and we’d like to print them out. We want to print out 3 things: the position of the runner, their name, and their time. The results are stored in a list of tuples:

>>> results = [('Thompson-Herah', 10.610), ('Fraser-Pryce', 10.740), ('Jackson', 10.760)]

We can use what we have learnt so far to achieve this in just a few lines of Python code:

>>> for i, data in enumerate(results, start=1):
... 	name, time = data[0], data[1]
... 	print('{}. {}, {}s'.format(i, name, time))

Result:

1. Thompson-Herah, 10.61s
2. Fraser-Pryce, 10.74s
3. Jackson, 10.76s

The position is printed by starting the counter at 1 via the start=1 optional argument. The name and time are the first and second elements of the tuple. Notice the use of string formatting to print out the results nicely.

Luckily for us, the results list came pre-sorted from fastest to slowest time. If this isn’t the case, you can sort the tuples in the list by either the first element (the name), or the second element (the time). To do this, you would need to take advantage of the built-in sorted() function. This is a little tricky, but try it out. You’ll find more information in the article How to Sort a List of Tuples in Python.

Practice Using enumerate() in Python

In this article, we showed you how to loop through a list and print out the index and the element using the enumerate() function. We also showed you how to apply this to a list of tuples.

We’d like to encourage you to use what you’ve learnt in this article, so you have the following homework assignment. First, download the marathon-data dataset. This is a CSV file containing the age, gender, split, and final time for participants in a marathon. Your task is to read the data into Python and print the data for the fastest 10 and slowest 10 competitors.

If you need some more practice reading in the data, take a look at our How to Read and Write CSV Files in Python course. Learning these fundamental skills early in your programming journey is important. You will use them regularly to build more complex and interesting programs. Happy coding!

Tags:

  • python
  • enumerate

You may also like

How to Sort a List of Tuples in Python
Learn how to sort a list of tuples in Python using sorted(), sort(), and other techniques.
Read more
7 Ways to Loop Through a List in Python
Learn several ways to loop through a list in Python, including for loops, while loops, and much more!
Read more
How to Write a For Loop in Python
Wondering how to write a for loop in Python? Check out some examples of iterating over a list, a tuple, a set, a dictionary, or a string in Python.
Read more
Subscribe to our newsletter Join our monthly newsletter to be notified about the latest posts.

How Do You Write a SELECT Statement in SQL?

What Is a Foreign Key in SQL?

Enumerate and Explain All the Basic Elements of an SQL Query

Quick links

  • Pricing
  • Blog
  • Vertabelo.com

Assistance

Need assistance? Drop us a line at [email protected]

Write to us

Follow us

LearnSQL Facebook We Learn SQL Facebook Linkedin LearnPython.com We Learn SQL Youtube
go to top
Copyright ©2016-2018 Vertabelo SA All rights reserved
Vertabelo
  • Terms of service
  • Privacy policy
  • Imprint