

This is what is looks like all put together: directions = [įor count, direction in enumerate(directions, start=1): Inside the loop we will print out the count and direction loop variables. for count, direction in enumerate(directions, start=1): We want to start counting at 1 instead of the default of 0. The enumerate() function will take in the directions list and start arguments. Then in the for loop, we create the count and direction loop variables. 'Head north on Broadway toward W 48th St', We first have to create the list of directions: directions = [ In this example, we want to print out a list of directions going from Times Square to the Juilliard School of Music in New York City, New York.
Python enumerate how to#
How to use a for loop and the enumerate() function in Python We can use the enumerate() function with a for loop to print out the values of an iterable with a counter.
Python enumerate update#
This function keeps track of the iterations so you don't have to remember to update the count variable. The return value of the enumerate() function is an object. If you omit the optional start argument, then the count is set to zero. enumerate(iterable, optional start argument) Python's built in enumerate() function takes in an iterable and an optional start argument. What is the enumerate() function in Python? Instead of incrementing a count variable ourselves, we can use the enumerate() function with the for loop. Now the count variable is no longer accurately keeping track of how many times we have looped over the list. If I altered the code, then this would be the new result printed to the console: dogs = While this approach does work, it presents a possible error.Ī common mistake would be to forget to increment the count variable. This is what the result would look like printed to the screen: We are also going to increment the count variable by 1 each time to keep track of how many times we have iterated over the list. We can use a for loop to go through the list and print each name. In this example, we have a list of dog names and a variable called count. Examples of iterables include lists, tuples, and strings. In Python, an iterable is an object where you can iterate over and return one value at a time. How to use a for loop without the enumerate() function in Python

In this article, I will show you how to use Python's enumerate() function with a for loop and explain why it is a better option than creating your own incrementing counter.īut first, let's take a look at how to accomplish this without the enumerate() function. When you're coding in Python, you can use the enumerate() function and a for loop to print out each value of an iterable with a counter.
