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

  • How to Check Python Version in Linux

    The knowledge of the correct version of python is important for many tasks. For example, we may want to install a library that requires a specific version of python to check if our system has that version already installed. For example, in the Terminal formatting tutorial using rich, we have learned about a library called rich, which is used for terminal formatting in python. Still, the library requires Python 3.6.1 or later installed in the system.

  • Python Defaultdict explained with examples

    In Python, a dictionary represents an unordered collection of data values that can be used to store data values in the same way a map can. The dictionary has a key-value pair, unlike other data types with a single value as an element. The key must be unique and unchanging, according to Dictionary. It means that a Python Tuple, unlike a Python List, can be used as a key.

  • Heapq in Python (with examples)

    Heapq is an abbreviation for heap and queues. They’re notable for tackling various challenges, including finding the best element in a dataset. We can optionally sort the smallest item first or vice versa when dealing with data collections. Python’s heapq belongs to the standard library. For the formation of a heap, this function uses a conventional Python list.

  • How to add data to a list in Python

    Python lists are one of the most common and popular data structure of python. Almost every python programmer uses them for writing great programs in python. Python lists are almost similar to the vectors in C++ or arrays in Javascript. Lists are mutable, which makes them editable after creation. Lists can contain elements like numbers, strings, dictionaries, tuple, boolean, lists, and any other python object.

  • How to install Python modules

    One of the reasons that Python is so valuable is that there are several packages that we can install that extend the capabilities of Python. For example, if we want MATLAB-like functionality matrices numerical analysis, you can use numpy, optimizers, and differential equation solvers. Further, several other packages like matplotlib help us plotting, while Pygame helps develop a graphical user interface and build diverse games. xlwings, on the other hand, allows us to interface with excel. In addition, we have others like open CV, computer vision, etc.

Leave a Reply

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