Jump to content

How to Use Enumerate Function in Python to Create Loops with Counters


Linux Hint

Recommended Posts

This article will explain usage of the “enumerate” function available in Python’s standard module library. Enumerate function allows you to assign an “index” or “count” to elements in any iterable object. You can then implement further logic on them as you will have access to both values and a count mapped to it.

Syntax and Basic Example

If you have used a “for” loop in other programming languages, especially “C” language and other languages having “C” style syntax, you may have specified a starting index in the loop. For reference, here is what a “for” loop looks like in “C” and other languages having similar syntax:

for (int i = 0; i < 10; i++)

{

    printf("%d\n", i);

}

The loop statement initializes a variable having a value of zero, checks that it is less than a threshold and increments it by one count after evaluating logic inside the loop block (if the stop condition is met). This way you can use an index and assign it to any objects referenced in your loop block. In comparison, here is what a for loop with same result looks like in Python:

for i in range(0, 10):

    print (i)

The “range” function in Python allows you to specify a number range sequence that has a default step of 1. You can change the step value by supplying a third argument. The second argument in the “range” function is used to set the threshold for stop condition. Both code samples produce the following output:

0

1

2

3

4

5

6

7

8

9

These loops work fine if you just want to generate some number sequence and associate them with some logic inside the loop statement. However, you might have to use another nested loop or use the “yield” function on any iterable type to assign them some sort of trackable count. The “enumerate” method makes it easy to assign indexes to iterables in one statement, thereby eliminating the need for running multiple nested loops. Have a look at this code sample:

numbers = ["zero", "one", "two", "three", "four", "five"]

enumerated_numbers = enumerate(numbers)

for index, item in enumerated_numbers:

    print (index, item)

The first statement defines a new variable called “numbers” and assigns an iterable (list type) to it. The second statement shows usage of the “enumerate” function where you supply an iterable to it as a mandatory argument. The third statement converts the “enumerated_numbers” variable to a list type object. By default, “enumerate” function generates an “enumerate” type object and not an iterable type, so you have to convert it. After running the code sample mentioned above, you should get the following output:

[(0, 'zero'), (1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')]

The “enumerate” function assigns a count to each element in an iterable type and creates tuples having paired values. By default, the count starts from zero.

Now that you have assigned a number to each element in an iterable type, you can easily loop over it without writing nested statements:

numbers = ["zero", "one", "two", "three", "four", "five"]

enumerated_numbers = enumerate(numbers)

for index, item in enumerated_numbers:

    print (index, item)

The code sample specified above will produce the following output:

0 zero

1 one

2 two

3 three

4 four

5 five

You can make the code shorter by using “enumerate” function inline, as shown in the sample below:

numbers = ["zero", "one", "two", "three", "four", "five"]

for index, item in enumerate(numbers):

    print (index, item)

Using Enumerate with a Different Starting Index

The “enumerate” function takes an optional argument where you can specify a starting index. By default it is zero, but you can change it by using “start” argument:

numbers = ["one", "two", "three", "four", "five"]

for index, item in enumerate(numbers, start=1):

    print (index, item)

In the second statement, “start=1” argument is used to change the starting point. After running the code sample specified above, you should get the following output:

1 one

2 two

3 three

4 four

5 five

Assigning Index with Steps

In the first section of this article, syntax for “for” loop in “C” language is shown where you can define steps between each subsequent count or index. The “enumerate” function in Python doesn’t have any such argument available so you can’t specify a step between counts. You can indeed write your own logic to implement steps inside the enumerated “for” loop block. However, there is a way to implement custom steps by writing minimal code. The following example shows implementation of steps using “zip” and “range” functions:

numbers = ["zero", "two", "four", "six"]

for index, item in zip(range(0, 7, 2), numbers):

    print (index, item)

The “zip” function allows you to create pairs by picking up elements having the same index from two or more iterables. So the “zip” function here picks up an element from the iterable returned from “range(0, 7, 2)” function and another element from “numbers” list and then pairs them both into a tuple. The end result is an identical implementation to the “enumerate” function but with custom steps specified as a third argument in the “range(0, 7, 2)” function (2 in this case). After running the code sample specified above, you should get the following output:

0 zero

2 two

4 four

6 six

Conclusion

The “enumerate” function in Python allows you to write concise code by assigning a number sequence to elements in an iterable object. This is really useful if you want to keep track of the index of items inside an iterable type. If you want to “enumerate” iterable types with custom steps, use the “zip” function explained in the last example.

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...