AppDividend
Latest Code Tutorials

Python Enumerate Function Tutorial With Example

0

Python Enumerate Function Tutorial With Example is today’s topic. Python enumerate() method adds counter to an iterable and returns the enumerate object. You can convert enumerate objects to list and tuple using list() and tuple() method respectively. A lot of times when we are dealing with the iterators, we also get to keep the count of iterations. Python eases the programmers’ task by providing the built-in function enumerate() for this task.

Python Enumerate Function Tutorial

The enumerate() function takes a collection (e.g., a tuple) and returns it as an enumerate object.

The enumerate() function adds a counter as the key of the enumerate object.

The syntax of enumerate() function is following.

enumerate(iterable, start)

An iterable parameter is an iterable object.

A start is a number, and it is the start number of an enumerate object.

See the following example.

# app.py

heir = ('bastard', 'jon snow', 'aegon targaryen')
result = enumerate(heir)
print(result)

The output is following.

 

Python Enumerate Function Tutorial

Convert Enumerate Object Into List

See the following example in which, first we use the enumerate function to create an enumerate object and then use the list method to convert the enumerate object into the list.

# app.py

heir = ['bastard', 'jon snow', 'aegon targaryen']
result = enumerate(heir)
print(result)
print(type(result))
print(list(result))

The output is following.

 

Convert Enumerate Object Into List

Provide the second parameter start

Let’s change the default counter and set the start value to 21 and see the output.

# app.py

heir = ['bastard', 'jon snow', 'aegon targaryen']
result = enumerate(heir, 21)
print(list(result))

The output is following.

 

Provide the second parameter start

Looping Over an Enumerate object

Let’s loop over through an enumerate object and print the one by one item in the console.

# app.py

heir = ['bastard', 'jon snow', 'aegon targaryen']
result = enumerate(heir, 19)

for item in result:
  print(item)

The output is following.

 

Python Enumerate Function Tutorial With Example

So, Python enumerate() function adds a counter to an iterable.

By default, enumerate() starts counting at 0, but if you give it a second integer argument, it’ll start from that number instead.

Finally, Python Enumerate Function Tutorial With Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.