Usually, when someone iterates through an iterable using the conventional loops (for and while), at times it becomes cumbersome to keep track of the count and the relative positions of the elements in the iterable. When using for loops, there is no need to assign a variable to keep the count of the elements; however, there is sometimes a need for a variable that changes inside the loop based on some conditions. 

It is common to use the enumerate method in Python to map the counter’s value along with the iterable items. It can serve both as a counter and as a way to maintain the indices of the elements in the iterable. 

What is Enumerate in Python?

In simpler words, the enumerate function takes as input, an iterable and adds a counter to each iterable element, and returns an enumerate object. The counter can also act as indices to each element which can be used to reference these elements at a later stage when required. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

How Does Enumerate() Work?

Enumerate() is a built-in function of Python. This function allows us to loop over something and have an automatic counter. And this function works by adding a counter to an iterable and returning it in the form of an enumerate object. The enumerate object can be used directly for loops or converted into a list of tuples using the list() method.

What Does Enumerate Do in Python?

Enumerate is a built-in function in python that allows you to keep track of the number of iterations (loops) in a loop. This enumerate object contains a count (from the start, which always defaults to 0) and a value obtained from iterating over the iterable object. It adds a counter to an iterable and returns it as an enumerate object. And this enumerate object can then be used directly for loops or converted into a list of tuples using the list () method. 

The syntax for enumerate is: enumerate (iterable, start=0).

How to Use Enumerate in Python?

The enumerate function can be used to iterate over a sequence of items in a list, tuple, or string. The function takes two arguments: the sequence to be iterated over, and the starting value for the enumeration. 

By default, the starting value is 0, but it can be specified as a keyword argument. The enumerate function returns an iterator that yields pairs of (index, value) for each item in the sequence.

Here is a simple example:

Syntax: enumerate(iterable, start=0)

print(index, item)

Output (for example):

0 apple

1 banana

2 cherry

Using Enumerate() On a List With the Start Index

The enumerate() function is a built-in function that takes a list and an optional start index as arguments. The start index defaults to 0 if not specified. This function returns an enumerate object, which is an iterator that yields pairs of values. And there are, 

  • The index of the item in the list, 
  • And the item itself.

This function can be useful when you need to keep track of the index of an item while iterating through a list. For example, you might want to print out a list of items with their corresponding indexes. 

To do this, you could use a for loop with the enumerate() function:

my_list = ['a', 'b', 'c']

for index, item in enumerate (my_list):

print(index, item)

This function would print out the following:

0 a

1 b

2 c

If you specify a start index, the index of the first item will be the specified start index, and the index of each subsequent item will be incremented by. 

For Example:

my_list = ['a', 'b', 'c']

for index, item in enumerate (my_list, 1):

print(index, item)

This function would print out the following:

1 a

2 b

3 c

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Enumerate Python Sets

Python sets are powerful data structures that can be used to store and manipulate data in various ways. Sets are unordered data collections, so they can't be used to index or slice data. Sets store data in a variety of ways, such as a list of unique values or a list of distinct values. And sets can perform some mathematical operations such as union, intersection, and difference.

Sets can be created from any iterable object, such as a list or a tuple. To create a set, simply use the set() function. 

For Example:

my_set = set([1, 2, 3])

Sets can also be created from other sets using the union(), intersection(), or difference() functions. 

For Example:

my_set = set([1, 2, 3])

other_set = set([2, 3, 4])

my_set.union(other_set)

set([1, 2, 3, 4])

my_set.intersection(other_set)

set([2, 3])

my_set.difference(other_set)

set([1])

Enumerate Python Tuples

Python tuples are one of the basic data structures that you can use to store a sequence of values. A tuple is similar to a list, except that it is immutable, meaning that you cannot modify the values in a tuple once it is created.

You can create a tuple by enclosing a comma-separated sequence of values in parentheses. 

For example, the following tuple contains the values 1, 2, and 3:

t = (1, 2, 3)

You can access the values in a tuple by using indexing, just like with a list. For example, the following code retrieves the first and second values in the tuple t:

t[0]

1

t[1]

2

You can also use negative indexing to retrieve values from a tuple, starting from the end of the tuple. 

For example, the following code retrieves the last value in the tuple t:

t[-1]

3

If you try to modify a value in a tuple, you'll get an error:

t[0] = 4

TypeError: 'tuple' object does not support item assignment

However, you can concatenate tuples together to create a new tuple:

t + (4, 5, 6)

(1, 2, 3, 4, 5, 6)

You can also create a tuple with a single value by including a trailing comma:

t = (1,)

Tuples are often useful when you want to create a tuple with only one value, but you can't use a list because you need an immutable data structure.

Enumerating a String

When working with strings in Python, it is often useful to enumerate the characters in the string. This process can be done with the built-in function enumerate().

Enumerate takes an iterable object (such as a string) and returns an enumerate object, which contains a list of tuples. Each tuple contains the index of the character and the character itself.

For example, if we have the string "hello", we can enumerate the characters like this:

for index, character in enumerate("hello"):

print(index, character)

...

0 h

1 e

2 l

3 l

4 o

As you can see, the first element in each tuple is the index of the character, and the second element is the character itself.

Enumerating a string can be useful when you need to process each character in a string individually, such as when you need to encrypt or decrypt a string.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Enumerate a Dictionary

In Python, a dictionary can be enumerated using the built-in function enumerate(). This function takes a dictionary as an argument and returns an enumerate object, which can then be used to iterate over the dictionary. 

The enumerate object returned by enumerate() has two properties: 

  • The first property is the index, which starts at 0. And it goes up to the number of items in the dictionary. 
  • The second property is the value, which is the value of the dictionary key at the corresponding index. 

For example, consider the following dictionary:

my_dict = {"a": 1, "b": 2, "c": 3}

We can enumerate this dictionary using enumerate():

for index, value in enumerate(my_dict): 

print(index, value) 

...

0 a 

1 b 

2 c

As we can see, the first property of the enumerated object is the index, and the second property is the value. We can access these properties using indexing:

for index, value in enumerate(my_dict): 

print(index, value, my_dict[value]) 

...

0 a 1 

1 b 2 

2 c 3

As we can see, the indexing allows us to access the value of the dictionary key at the corresponding index. This is how we can enumerate a dictionary in Python.

Syntax of Enumerate in Python

The syntax of the in-built enumerate function is  - 

enumerate(iterable, start_index)

Parameters:

  • Iterable: An iterable is an object that can be looped over. Examples of iterables in Python are tuples, lists, sets, etc.
  • Start_Index: This parameter is optional and defines the value from which the count should start for the first element in the loop. This count is then incremented by 1 for the succeeding elements, till the end. If this parameter is not defined, then the default value is 0.

Return Value:

The return value of the enumerate function is the enumerate object which contains tuples with the count value and the item or the element of the iterables.

For Loops Vs. Enumerate in Python

There are two ways to iterate through a sequence in Python: the for loop and the enumerate function.

  • Loop is the traditional way to iterate through a sequence. It is simple to use and easy to understand. It allows you to iterate over a sequence of items without keeping track of the index of the current item. However, it can be inefficient if you are dealing with a large sequence.
  • The enumerate function is a built-in function that allows you to iterate through a sequence and keep track of the index of each element. This function can be useful if you need to access the index of each element in the sequence. However, it can be more difficult to understand than the for loop.

How to Use the Python Enumerate Method? 

Python's enumerate method allows you to iterate over a list, tuple, or dictionary and return a tuple containing the index of each element and the element itself. This is a convenient way to keep track of both the element and its position on a list. To use the enumerate method, you need to pass in the list, tuple, or dictionary that you want to iterate over.

Adding a Starter Index Value

The enumerate method allows you to keep track of the index values of a list as you iterate through it. This method can be particularly useful when you need to access a specific element in the list based on its position. 

For example, let's consider that  you have a list of numbers and you want to find the sum of all the elements at even index positions. With the enumerate method, you can easily keep track of the index values and sum the elements accordingly.

For Example:

# Add starter index value

print(index, item)

# Output

0 a

1 b

2 c

Become a Certified UI UX Expert in Just 5 Months!

With The Best-in-class UI UX ProgramExplore Program
Become a Certified UI UX Expert in Just 5 Months!

Conditional Statements to Skip Items

If you're using enumerate to iterate over a sequence, there may be times when you want to skip over certain items. This process can be accomplished by using a conditional statement in the loop. 

For example, let's say you have a list of numbers but you only want to print the even ones. You can do this by using the modulo operator (%) to check for a remainder of 0:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for i, num in enumerate(numbers):

if num % 2 == 0:

print(num)

This code will print 2, 4, 6, 8, 10.

Unpacking Arguments With Enumerate()

When you're working with lists, you might want to enumerate them so that you can keep track of what item is at what index. If you have a list of arguments that you want to unpack, you can use the enumerate() function to do so.

For example, say you have a list of arguments that you want to unpack into individual variables. You can use the enumerate() function to do this:

args = [1, 2, 3]

for index, arg in enumerate(args):

print(index, arg)

Print output:

0 1

1 2

2 3

You can also use the enumerate() function to unpack a list of tuples:

tuples = [(1, 2), (3, 4), (5, 6)]

for index, (arg1, arg2) in enumerate(tuples):

print(index, arg1, arg2)

Print output:

0 1 2

1 3 4

2 5 6

Example 1:

Let’s consider a simple example where loops are used to print the index along with the items of a list.

Program:

letters = ["a", "b", "c", "d", "e", "f", "g"]

index = 0

for letter in letters:

print(index, letter)

index += 1

Output: 

LoopsVs.Enumerate_exp1

Here, you saw the use of a variable called index, to keep track of the count of the elements along with the index of each element in the iterable. Try another method to do the same.

Example 2:

You can also use range along with the length function to perform the same function.

Program: 

letters = ["a", "b", "c", "d", "e", "f", "g"]

for index in range(len(letters)):

print(index, letters[index])

Output:

LoopsVs.Enumerate_exp2

This method is also inefficient since you have to use the length function to iterate over the iterables to find the count.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Example 3: 

Now, use the enumerate function to carry out the same operation. The enumerate function saves the memory of using an extra variable, and the returned value is a simple reference to the memory, and not an actual list or iterable of items.

Program:

letters = ["a", "b", "c", "d", "e", "f", "g"]

for index, value in enumerate(letters):

print(index, value)

Output:

LoopsVs.Enumerate_exp3

It is not necessary to keep track of a separate count variable, advance it in each iteration, or go through the hassles of maintaining indices separately. Everything is handled by the enumerate function.

If you return the type of the enumerated object, you will find that it’s just a reference to a memory location.

letters = ["a", "b", "c", "d", "e", "f", "g"]

print(enumerate(letters))

Output:

LoopsVs.Enumerate_exp3_1

Playing with the Start Parameter

You can mention a different starting value in the start parameter. The default is 0, in case you mention a different value, the counting starts from that value and keeps on incrementing for all the items in the iterable.

Program:

letters = ["a", "b", "c", "d", "e", "f", "g"]

enumerated_list = list(enumerate(letters, 20))

print(enumerated_list)

Output:

StartParameter

As you can see, the starting index has now changed to the one specified in the second parameter.

Looping Over Enumerate Object in Python

In this example, try to loop over an enumerate object using a simple for loop. 

Program: 

letters = ["a", "b", "c", "d", "e", "f", "g"]

enumerated_object = enumerate(letters)

for i in enumerated_object:

print(i)

Output:

Looping_1

You can see that each object is a tuple inside the enumerated object that is returned.

Useful Tips for Using Enumerate in Python

  • Use enumerate() when you want to track the index of each item in an iterable: enumerate() allows you to loop over a collection of items while keeping track of the current item index. This process can be useful when you need to access the index in the loop body.
  • Use enumerate() to simplify complex list comprehensions: enumerate() can simplify complex list comprehensions by providing a more efficient way to iterate over the values in the list. This simplification can help reduce code complexity and make your code more readable.
  • Use enumerate() to improve the performance of your code: When you need to iterate over a collection of items, using enumerate() can improve the performance of your code. This benefit is because enumerate() creates an iterator for the collection, which is more efficient than looping through each item.

Advantages of Using Enumerate in Python

  • You can use enumerate on any iterable, be it lists, sets, dictionaries, strings, objects, etc. 
  • Enumerate keeps your code clean by performing the same function with fewer lines of code.
  • You can keep track of the count of elements along with the index of each element through enumerating without having to maintain separate variables for each of them and incrementing the counter.
  • It’s an automatic counter and can be used to change the starting value of the index as well, by specifying the appropriate value in the second parameter.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Disadvantages of Using Enumerate in Python

  • Enumerate takes up more memory due to the added counter.
  • Enumerate is not apt for parallel computing, as the output order is not guaranteed.
  • Also, it is not suitable for large data sets due to computational overhead.

Python Iterators Refresher 

Python iterators are a type of object that allows you to iterate over a sequence of values. They are a key part of the language and are used for loops, comprehensions, and other places where you need to iterate over a sequence of values.

There are Two Types of Iterators in Python:

  1. The iterator protocol: This is the standard way to create an iterator. It defines two methods, __iter__() and __next__().
  2. The yield statement: This is a special type of iterator that is used to create generators. Generators are a type of iterator that allows you to generate values on the fly.

Examples:

In Python, an iterator is an object that implements the iterator protocol. This protocol consists of two methods: __iter__() and __next__().

  • The __iter__() method is used to initialize the iterator. It is called when the iterator is first created. 
  • The __next__() method is used to retrieve the next element from the data structure. It is called on each iteration of the loop.

We'll start iterators by creating a simple data structure: a list of numbers.

numbers = [1, 2, 3, 4, 5]

We can create an iterator for this list using the built-in iter() function:

iterator = iter(numbers)

Now we can use the iterator to loop through the list:

for num in iterator:

print(num)

This code will print each number in the list to the console.

We can also use the iterator to perform operations on each element. 

For example, we can use the next() function to retrieve the next element from the iterator:

num = next(iterator)

This code will retrieve the first element from the iterator (1). We can then use this element in our code.

Iterators are a powerful tool for working with data. By using iterators, we can efficiently loop through data structures and perform various operations on each element.

If you're eager to gain the skills required to work in a challenging, rewarding, and dynamic IT role - we've got your back! Discover the endless opportunities through this innovative Post Graduate Program in Full Stack Web Development course designed by our partners at Caltech CTME. Enroll today!

Conclusion

In this guide, you have seen one of the best alternatives to the messy for loops in Python. You saw a basic introduction of the enumerate method in Python, along with the syntax and parameters that it accepts. This tutorial also explored the iterables that it takes as input, played with the start_index parameter, and saw a bunch of examples demonstrating how you can use enumerate instead of conventional for loops in python. 

Lastly, you learned some useful tips along with some advantages of using this method over loops. Enroll in our Post Graduate Program in Full Stack Web Development course in collaboration with Caltech CTME. In just a few months, you'll learn modern coding techniques with bootcamp-level intensity and gain all you need to be a full-stack technologist.

We certainly hope that with the help of this guide, you will get hands-on experience working with enumerating in Python and be able to adopt it without a second thought. Have any questions for us? Leave them in the comments section, and our experts will get back to you on the same, as soon as possible!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 27 Nov, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449