CODINGTHOUGHTS

A blog about C#, Python, Azure and full stack development

Python enumerate Function

The Python enumerate function adds a counter to an iterable (like a list or a string) and returns it as an enumerate object. This object can then be used in loops to iterate over both the index (or position) and the value of items in the iterable.

Syntax

The basic syntax of the enumerate() function is:

enumerate(iterable, start=0)
  • iterable: The iterable you want to enumerate.
  • start: The starting value of the counter. By default, it starts at 0.

Basic Usage

Let’s look at a simple example:

fruits = ["apple", "banana", "cherry", "date"] 
for index, value in enumerate(fruits): 
  print(index, value)
  
# will output: 0 apple 1 banana 2 cherry 3 date

In the example above, the enumerate() function adds a counter to the fruits list, allowing us to access both the index and the value in the for loop.

Advanced Usage

Starting from a different index

By default, the counter starts at 0. However, you can start it from any number using the start parameter:

python

for index, value in enumerate(fruits, start=1): print(index, value)

# outputs: 1 apple 2 banana 3 cherry 4 date

Using enumerate() with strings

Not just lists, enumerate() can be used with any iterable, including strings:

word = "hello" 
for index, letter in enumerate(word): 
  print(index, letter)
  
# outputs: 1 apple 2 banana 3 cherry 4 date

Combining enumerate() with list comprehensions

Python’s list comprehensions provide a concise way to create lists. You can combine them with enumerate() for powerful one-liners:

squared_values = [(index, value**2) for index, value in enumerate(range(5))]
print(squared_values)

# outputs: [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)]

Posted

in

by

Tags: