Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Enumeration in Python

Last updated by Ashwin Ramachandran on Sep 25, 2024 at 10:59 PM | Reading time: 6 minutes

The fast well prepared banner

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

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

Enumeration in Python
Hosted By
Ryan Valles
Founder, Interview Kickstart
strategy
Our tried & tested strategy for cracking interviews
prepare list
How FAANG hiring process works
hiring process
The 4 areas you must prepare for
hiring managers
How you can accelerate your learnings

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

Last updated on: 
October 10, 2024
Author

Ashwin Ramachandran

Head of Engineering @ Interview Kickstart. Enjoys cutting through the noise and finding patterns.

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

Register for our webinar

How to Nail your next Technical Interview

1
Enter details
2
Select webinar slot
First Name Required*
Last Name Required*
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.

Enumeration in Python

Worried About Failing Tech Interviews?

Attend our webinar on
"How to nail your next tech interview" and learn

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Our tried & tested strategy for cracking interviews
blue tick
How FAANG hiring process works
blue tick
The 4 areas you must prepare for
blue tick
How you can accelerate your learnings
Register for Webinar
entroll-image