Enumerate() in Python

Enumerate() in Python

When working with iterators, we frequently need to track how many iterations have been completed. Python makes this work easier for programmers by including an enumerate() function. Enumerate() method adds a counter to an iterable and returns it as an enumerating object. This enumerated object can then be used in loops directly or converted to a list of tuples with the list() method.

Enumerate() in Python

Syntax

enumerate(iterable, start=0)

Enumerate() Parameters

  • Iterable: It refers to any object that supports iteration
  • Start: It refers to the index value from which the counter is to be started; by default, it is 0
# Python's program illustrating the enumeration function
languages = ["Java","Python","JavaScript"]
new_language = "C++"

# creating enumerate objects
obj_one = enumerate(languages)
obj_two = enumerate(new_language)

print ("Return type:",type(obj_one))
print (list(enumerate(languages)))

# changing start index to 2 from 0
print (list(enumerate(languages,2)))
illustrating the enumeration function
illustrating the enumeration function

Enumerate() objects in loops

# Python's program illustrating the enumeration function in loops
languages = ["Java","Python","JavaScript"]

# printing the tuples in object directly
for lang in enumerate(languages):
  print(lang)

# changing index and printing separately
for count,lang in enumerate(languages,100):
  print(count,lang)

#getting desired output from tuple
for count,lang in enumerate(languages):
  print(count)
  print(lang)
enumeration function in loops
enumeration function in loops

The enumerate() function returns an enumerated object from a collection (such as a tuple). The counter is added as the key of the enumerated object by the enumerate() function.

Example: converting a tuple into an enumerate object

laptops = ('Apple', 'HP', 'DELL')
y = enumerate(laptops)
list(y)
converting a tuple into an enumerate object
converting a tuple into an enumerate object

How does enumerate() work?

The enumerate() function returns an iterator called an enumerate object. A tuple comprising the index and element at that index is returned for each element fetched from this enumerate object: (index, element). With the for loop’s every iteration, the elements of the returned tuple are assigned to the index and element variables. To put it another way, the returned tuple is unpacked within the for-statement:

for index, element in enumerate(num_list):
  
  # similar to:
  
index, element = (index, element)

The following example demonstrates these tuples more clearly:

students_list = ['Ann', 'Joy', 'Thomson']
list(enumerate(students_list))
enumerating students list
enumerating students list

The list() function on the enumerated object (the iterator) provides a list of tuples, each containing the index and its matching element or value.

Example 1: How does enumerate() work in Python?

laptops = ['HP', 'DELL', 'Chromebook']
enumerateLaptops = enumerate(laptops)
print(type(enumerateLaptops))

# converting to list
print(list(enumerateLaptops))

# changing the default counter
enumerateLaptops = enumerate(laptops, 10)
print(list(enumerateLaptops))
enumerate() in work
enumerate() in work

Example 2: Enumerate object – Looping Over

laptops = ['HP', 'DELL', 'Chromebook']

for machine in enumerate(laptops):
  print(machine)

print('\n')

for count, machine in enumerate(laptops):
  print(count, machine)

print('\n')
# changing default start value
for count, machine in enumerate(laptops, 100):
  print(count, machine)
enumerate object
enumerate object

Conclusion

The Python library includes a built-in method called Enumerate(). It receives a collection of tuples as input and produces an enumerated object. Enumerate() adds a counter to each item of an iterable object and delivers an enumerate object as an output string in Python.

Python’s enumerate() function helps you create Pythonic for loops when you need a count and the value from an iterable. Enumerate () gives a tuple containing the number and value, which means you don’t have to increment the counter yourself is a significant plus. It also gives you the option of changing the counter’s beginning value.

Similar Posts

  • Python Flask and React

    Modern online applications are frequently created using a server-side language that serves data via an API and a front-end JavaScript framework that presents the data to the end-user easy-to-use. Python is a dynamic programming language that is widely used by businesses and professionals. The language’s core ideals indicate that software should be readable and straightforward, allowing developers to be more productive and happier.

  • Deque Python with examples

    Python’s “collections” module is used to implement the Deque (Doubly Ended Queue). When we need faster append and pop operations from both ends of the container, the deque is favored over lists because deque offers an O(1) time complexity for append and pop operations. In contrast, lists offer an O(n) time complexity.

  • How to Add Numbers in Python

    There are several ways to add numbers in Python, depending on the type of numbers and the context in which they are used. Python has numerous operators such as using the + operator, the sum() function, the += operator, the numpy library, the operator module, reduce() function, the fsum() function, accumulate() function, the mean() function, and the operator.add() method. The method chosen will depend on the specific requirements of your project. Here are a few examples:

  • Pandas ffill function with examples

    This tutorial will explore the Python pandas DataFrame.ffill() method. This method adds the missing value to the DataFrame by filling it from the last value before the null value. Fill stands for “forward fill.” By using this method on the DataFrame and learning the syntax and parameters, we will be in a position to solve examples and comprehend the DataFrame.ffill() function.

  • Time Series Analysis in Python

    Time series analysis is an essential concept that has practical applications in our day-to-day living. The skills you acquire from mastering time series analysis will place you in a good position to work as a data scientist, a finance analyst, or a data analyst. By acquiring these skills, you will help handle issues such as estimating the risk of a portfolio’s stock, predicting certain properties in real estate, and making predictions on the performance of things like loans.

Leave a Reply

Your email address will not be published. Required fields are marked *