About usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Enumeration in Python

Enumeration, by definition, means defining the list of things in terms of numbers, one by one. It provides serial order to a list of objects. It is simply assigning a unique identifier to every object of the list or counting the list of objects one by one in order.

In this article, we’ll cover how enumeration works in Python:

  • Built-in enumerate() function in Python
  • Enumerating a list in Python
  • Strength and weakness of the enumerate() function in Python
  • Problems on enumerate() in Python
  • FAQs on enumerate() in Python

Built-in enumerate() Function in Python

Python’s enumerate() function helps you keep count of each object of a list, tuple, set, or any data structure that we can iterate (known as iterable).

For example, suppose we have a list of planets (Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune). If we consider the order from left to right, we can say that the first planet is Mercury and the eighth is Neptune. So we’re basically assigning a number to each planet’s name or, in other words, we’re enumerating the planets.

Parameters of enumerate()

enumerate() accepts two arguments: iterable and start. 

  • iterable: List, tuple, set, or any data structure that supports iteration
  • start: Default parameter. Defines from where the counting begins. If not passed, its value will be 0.

Return Value of enumerate()

enumerate() returns an enumerated object, which is iterable, and it can also be converted into other iterable data structures such as list and tuple.

Example:

user_skill_list = ["Cpp", "Java", "Python"]
enumerate_object = enumerate(user_skill_list) # Excluding start parameter
print(type(enumerate_object)) # Output: <type 'enumerate'>

enumerate_list = list(enumerate_object) # Convert enumerate object to list

print(enumerate_list)

enumerate_object = enumerate(user_skill_list, start=5) # Defining start parameter
for enumerated_language in enumerate_object:
    print(enumerated_language)

'''
Output:
<type 'enumerate'>
[(0, 'Cpp'), (1, 'Java'), (2, 'Python')]
(5, 'Cpp')
(6, 'Java')
(7, 'Python')
'''

Enumerating a List in Python

As you know, Python’s enumerate() allows you to enumerate every iterable data structure. List is an iterable data structure and hence can be enumerated. Not only one-dimensional lists, but we can enumerate any list irrespective of the dimension. This can be done by passing each instance of the list object to enumerate() and keeping records of each enumerated object for further processing.

We have already covered a 1D list in the example above. Here, we have implemented a two-dimensional list of programming languages. Let’s see how we can enumerate each value of the list.

user_skill_list = [
    ["Cpp", "Java", "Python"],
    ["HTML", "Javascript", "CSS"],
    ["Python", "R", "Julia"]
]

enumerated_user_skill_list = enumerate(user_skill_list, start=5) # Enumerate double dimension list
for counter, language_list in enumerated_user_skill_list:
    print(counter, language_list)

enumerated_object_list = [enumerate(lang_list) for lang_list in user_skill_list] # enumerating each list object in user_skill_list

for enumerated_object in enumerated_object_list:
    for counter, lang in enumerated_object:
        print(counter, lang)

'''
Output:
5 ['Cpp', 'Java', 'Python']
6 ['HTML', 'Javascript', 'CSS']
7 ['Python', 'R', 'Julia']
0 Cpp
1 Java
2 Python
0 HTML
1 Javascript
2 CSS
0 Python
1 R
2 Julia
'''

Strengths and Weaknesses of the enumerate() Function in Python

Strengths:

  • enumerate() is a Pythonic way of counting the list of objects. It avoids the use of for loop and thus makes the code a little bit cleaner.
  • enumerate() has the flexibility to start counting from any number you want by specifying the value of the start parameter.
  • enumerate() helps in avoiding the off-by-one error or off-by-one bug.

Weakness:

  • enumerate() only counts in a consecutive way, i.e., start from any number i and then increment it by 1. For example, i, i+1, i+2, i+3, i+4 and so on. If you want to assign values in a difference of 2 or 3, then you have to use a for loop.

Problems on enumerate() in Python

Problem 1: Find the sum of all even index values in Python.

In this problem, we will enumerate the list, and then based on the enumerated counter value of each object of the list we will find the sum of the values.

num_list = [4, 5, 3, 2, 11, 10, 33]

total_sum = 0

for counter, value in enumerate(num_list, start=1):
if counter % 2 == 0:
total_sum += value

print("Sum is -", total_sum)

'''Output
Sum is - 17
'''

Problem 2: Given a string of only lowercase characters. Find the difference between the sum of ASCII value of all vowels and the sum of ASCII value of all consonants. 

Here, we will create a dictionary object ascii_char_map, which will store the ASCII value of all lowercase characters corresponding to the character itself as a key. Then we iterate the input_string and check if the current character x is a vowel. If yes, we add it to the vowel_sum; else, we add it to the consonant_sum. Finally, we find the difference between the two of them.

'''input
alsdjfksjfdasldjf
'''

alphabets = "abcdefghijklmnopqrstuvwxyz"
ascii_char_map = {character: counter for counter, character in enumerate(alphabets, start=97)}

input_string = input()

vowel_sum = 0
consonant_sum = 0

for x in input_string:
        if x in ['a', 'e', 'i', 'o', 'u']:
                vowel_sum += ascii_char_map[x]
        else:
                consonant_sum += ascii_char_map[x]

print("Sum of vowel -", vowel_sum)
print("Sum of consonant -", consonant_sum)
print("Difference -", abs(consonant_sum - vowel_sum))

'''
Output
Sum of vowel - 194
Sum of consonant - 1592
Difference - 1398
'''

FAQs on enumerate() in Python

Question 1: Does Python2 support enumerate()?

Answer: Python2 and Python3 both support enumerate(). However, the start parameter was added in Python2.6. This parameter helps define the start value of enumeration, i.e., it defines the initial value from where the counting begins.

Question 2: How do you use enumerate() on tuple or string in Python?

Answer: Using enumerate() on tuple or string is very similar to using this function on a list in Python. Let’s see how enumerate() works on a tuple:

language_list = ('Python', 'C++', 'JAVA', 'JavaScript')
enumerated_language_list = enumerate(language_list)

for counter, language in enumerated_language_list:
    print(counter, language)

'''
Output
0 Python
1 C++
2 JAVA
3 JavaScript
'''

Let’s see how enumerate() works on a string:

user_string = "abcdefghijkl"

enumerated_language_list = enumerate(user_string)

for counter, character in enumerated_language_list:
    print(counter, character)

'''
Output
0 a
1 b
2 c
3 d
4 e
5 f
6 g
7 h
8 i
9 j
10 k
11 l
'''

Preparing for a Tech Interview? 

If you’re looking for guidance and help with getting started, sign up for our free webinar. As pioneers in the field of technical interview preparation, we have trained thousands of software engineers to crack the toughest coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

---------

Article contributed by Problem Setters Official

Attend our Free Webinar on How to Nail Your Next Technical Interview

Recommended Posts

All Posts