Progress

Python enumerate() function: With Examples

Python enumerate() function: With Examples

Python is the ocean of built-in functions and methods which are very helpful. The enumerate function is one of the most useful things in Python which peoples ignore.

Python Programming Examples:

What is Enumerate Function in Python?

Enumerate function adds a counter to any iterable. The return format of the enumerate function is a tuple (count, element).

Here is an example that explains the working of the enumerate function in Python.

Copy
evenNums = [2,4,6,8,10,12]
    for i in enumerate(evenNums):
        print(i)
Output
(0, 2)
(1, 4)
(2, 6)
(3, 8)
(4, 10)
(5, 12)
None

Arguments of Enumerate Function

The enumerate function takes two arguments.

enumerate(iterable, start=0)
  • Iterable can be any data structure which supports iteration like list, set, tuple, dictionary.
  • The start argument takes an integer. It is the starting value of the counter which the enumerate function return with items.

Example of start argument of the enumerate function.

Copy
evenNums = [2,4,6,8,10,12]
    for i in enumerate(evenNums, start=5):
        print(i)
Output
(5, 2)
(6, 4)
(7, 6)
(8, 8)
(9, 10)
(10, 12)
None

Real Life usage of Enumerate function of Python

enumerateExample.py
Copy
langList = ["Python", "C", "Java", "C++", "Javascript", "PHP", "SQL", "HTML and CSS"]
print("Here are the list of languages that I have Used:")
for i in enumerate(langList ,start=1):
    print("{0}. {1}".format(i[0], i[1]))
Output
Here are the list of languages that I have Used:
1. Python
2. C
3. Java
4. C++
5. Javascript
6. PHP
7. SQL
8. HTML and CSS

This is very basic example of enumerate function for beginners understanding. There are many other advance uses of the enumerate which you will learn while using it.

Share your own example of the enumerate in Python in comments.

Share the Post ;)

Related Posts