Understanding the Python enumerate() Method

Python Enumerate()

The enumerate() method is used when there is a need to iterate over a list, tuple or string with the item’s index value. This helps us to keep count of iterable.

This tutorial will cover the enumerate() method in depth, we will also cover how to use this method to iterate through a list, string and tuple, and finally, we will see how to convert enumerate to JSON for further use.

Python enumerate() Method

Python’s built-in enumerate() method converts a passed sequence into an object containing the same elements with their corresponding index in the form of a tuple.

This index is a counter for the elements, by default it starts from 0 for the first element in the sequence. It can be changed by initialling its values by passing an additional argument after the sequence you want to convert into an enumerating object.

Syntax:

Below is the syntax for using this method.

enumerate(iterable, start)

Where,

  • iterable is any sequence for which we need to add an individual element index,
  • start is an optional argument that initialises the starting value with which the indexing would start. If not passed, the default value is set to 0.

Using the enumerate() Method in Python

The enumerate() method in python can convert any iterable sequence into a enumerate object with added indices. This sequence can be a list, string, or tuple. But it is not allowed to be a dictionary or a set, as they are not sequences.

This function in python can be used when there is a requirement to attach the index value to the respective elements, such as when you perform the iteration of the loop, you can use this method to get both the index and the object itself at the same time without using any extra code.

This method is also useful when creating a dictionary where it is required to have a key, or when generating the Python JSON from a sequence.

Now, let us try this on different iterable to see if it works.

Enumerate a List in Python

When we pass a list to this method, it adds the elementary indices as the first value into the tuple element. The returned iterable is of type enumerate.

To print this returned object, we can use a simple for loop traversing through it. Note, this time we can access both the element index and element value at the same time.

Below is the code to convert a list into an enumerate object and print the index with the corresponding value:

list1 = [ 11, 22, 33, 44]

enumerate_list = enumerate(list1)
print("Enumerated list now looks like: ", list(enumerate_list))

#print the index and corresponding value for enumerated list1
for i, item in enumerate(list1):
    print("Index = ", i,"  :  ","value = ",item)

Output:

Enumerated list now looks like:  [(0, 11), (1, 22), (2, 33), (3, 44)]
Index =  0   :   value =  11
Index =  1   :   value =  22
Index =  2   :   value =  33
Index =  3   :   value =  44

Here,

  • list1 is a list with some initial values in it. We pass it to the enumerate() method and store the returned object inside a variable,
  • When we type-caste this object into a list and try to print it using the print() method, we can observe that each element of the list is now converted into a tuple with added index,
  • Nearly we use for loop with two variables i and item to traverse through the returned object. In this way, we can access both index(i) as well as the corresponding element (item) at the same time.

The enumerate() works in the same way for a string and tuples too.

Enumerate a String in Python

The enumerate() method can be used to convert a string into an enumerate object with added indices.

It will treat each character of a string as a value itself and associate a corresponding index to it which by default starts with 0.

Below is the code to convert a string into an enumerate object and print the index with the corresponding character:

string1 = "AskPython"

enumerate_string = enumerate(string1)
print("Enumerated list now looks like: ", list(enumerate_string))

#print the index and corresponding character for enumerated string
for i, item in enumerate(string1):
    print("Index = ", i,"  :  ","character = ",item)

Output:

Enumerated list now looks like:  [(0, 'A'), (1, 's'), (2, 'k'), (3, 'P'), (4, 'y'), (5, 't'), (6, 'h'), (7, 'o'), (8, 'n')]
Index =  0   :   character =  A
Index =  1   :   character =  s
Index =  2   :   character =  k
Index =  3   :   character =  P
Index =  4   :   character =  y
Index =  5   :   character =  t
Index =  6   :   character =  h
Index =  7   :   character =  o
Index =  8   :   character =  n

Here,

  • We initialize a string string1 and store the returned enumerate object in a variable,
  • Then the list type-casted object is printed. As we can see it is a list of tuples containing individual character elements with their respective indices,
  • Again we traverse through this object using a for loop and print out the elements with indices.

Enumerate a Tuple in Python

Tuple in python is used to store multiple values in the form of a single variable which is immutable. We can also use this method to convert a tuple into a enumerate object just like in the case of a list and string.

Below is the code to convert a tuple into an enumerate object and print the index with the corresponding value:

tuple1 = ('Jacks', 'Rack', 'Jon', 'Smith')

enumerate_tuple = enumerate(tuple1)
print("Enumerated list now looks like: ", list(enumerate_tuple))
 
#print the index and corresponding value of each item in the tuple
for i, item in enumerate(tuple1):
    print("Index = ", i,"  :  ","value = ",item)

Output:

Enumerated list now looks like:  [(0, 'Jacks'), (1, 'Rack'), (2, 'Jon'), (3, 'Smith')]
Index =  0   :   value =  Jacks
Index =  1   :   value =  Rack 
Index =  2   :   value =  Jon  
Index =  3   :   value =  Smith

Here,

  • We initialize a tuple tuple1 with some values in it,
  • Then pass it to the enumerate() method and store the returned value in a variable,
  • Then print the list type-casted object. As we can see it is a list of tuples containing individual elements with their respective indices, 
  • Again we traverse through this object using a for loop and print out the elements with indices.

Python enumerate() with the Start parameter

As mentioned earlier, the start parameter is an optional parameter that determines from which value the indexing would start for the object returned by the enumerate() python method.

Let us look at an example where we try to change the indexing of a list with starting index 0 to a list with starting index 20.

list1 = [11, 22, 33, 44]

enumerate_list = enumerate(list1)
print("Enumerated list now looks like: ", list(enumerate_list))

#without start
print("Without Start:")
for i, item in enumerate(list1):
    print("Index = ", i,"  :  ","value = ",item)

#with start = 20
print("With Start:")
for i, item in enumerate(list1, 20):
    print("Index = ", i,"  :  ","value = ",item)

Output:

Enumerated list now looks like:  [(0, 11), (1, 22), (2, 33), (3, 44)]
Without Start:
Index =  0   :   value =  11
Index =  1   :   value =  22
Index =  2   :   value =  33
Index =  3   :   value =  44
With Start:
Index =  20   :   value =  11
Index =  21   :   value =  22
Index =  22   :   value =  33
Index =  23   :   value =  44

Here, we initialize a list containing different numbers, then use enumerate() method and print the type-casted object, you can observe that without passing the optional argument to this method, the index of the first element is 0(i.e index count starts from 0) whereas after passing the optional argument as 20 to this method, the index of the first element is 20(i.e index count starts from 20). Hence, the output is justified.

Converting Enumerate into JSON Object

An iterable is converted into JSON(JavaScript Object Notation) as it is the most convenient form of data sharing. It is small in size making it fast to transfer over the network for the transmission of information.

Directly converting an iterable to JSON is not a good approach as a JSON should have key-value pairs.

For converting an iterable to JSON, we have to convert it into enumerate object to add the index value then convert it into a Python Object( Dictionary) which contains key-value pairs then pass it inside the json.dumps() method which returns a JSON.

Example:

import json

data = ['Jacks', 'Rack', 'Jon', 'Smith']

enumerate_object = enumerate(data,1)

dict_enumerate = dict(enumerate_object)

json_enumerate = json.dumps(dict_enumerate)

print(json_enumerate)

Output:

{"1": "Jacks", "2": "Rack", "3": "Jon", "4": "Smith"}

Here, 

  • We import the JSON module to use the json.dumps() method,
  • Then create a list containing various values,
  • Then convert it into an enumerating object(we have passed 1 as an additional argument to start the index from 1),
  • Then use dict() method to further convert it into a Python dictionary,
  • Then use the json.dumps() method to finally produce JSON from the dictionary,
  • Then print the result.

If you still find the above code confusing, in another tutorial, How to convert Dictionary into JSON in Python? we have briefly covered the process of converting a python dictionary to JSON.

Conclusion

The enumerate() is a built-in function in Python that takes a sequence or iterate(a thing that is iterable) and converts it into an iterable object containing tuples. Each tuple has an index with the respective element of the sequence. The index value by default starts with 0 but can also be initialized by passing it to the method as an additional argument after the sequence.

Keep in mind that this method only works for sequences. Hence, dictionaries or sets cannot be converted.

This method is useful in various cases, such as when there is a requirement to associate elements with their index values, when looping through a list instead of using adding variable i for the count you can use index values, when converting a list into a python dictionary, or when generating the python JSON from a list.

Hope this tutorial helps you to understand the enumerate() method in Python.

Reference

https://docs.python.org/2.3/whatsnew/section-enumerate.html