Python enumerate working example code

Python Enumerate() method



Python enumerate working example code

The enumerate() function in Python is a built-in utility that makes looping easier and cleaner. It adds a counter (index) to any iterable, returning pairs of index and value — letting you access both during iteration.

It essentially turns an iterable into an iterator of index–value tuples, making loops more readable and Pythonic.

 # Example 
fruits = ['apple', 'banana', 'cherry'] 
Output: (0, 'apple') (1, 'banana') (2, 'cherry') 

python enumerate method example

What is enumerate() in Python?

The enumerate() function adds an automatic counter to an iterable (like a list, tuple, or string) and returns it as an enumerate object, which can be looped through or converted into a list of tuples.

Syntax: enumerate(iterable, start=0)

Parameters:

Parameter	Description
iterable	The sequence you want to iterate over (e.g., list, tuple, string)
start	        The starting index (default is 0)

Returns:
An enumerate object, which produces (index, element) pairs.

Method 1: Basic Use of enumerate()

The most common way to use enumerate() is inside a for loop.

fruits = ['apple', 'banana', 'cherry']

for index, fruit in enumerate(fruits):
print(index, fruit)

Output:

 0 apple 1 banana 2 cherry 

The simplest way to get both index and value while looping.
Python enumerate working example code

Method 2: Using start Parameter to Change the Counter

You can start the index from any number using the start parameter.

fruits = ['apple', 'banana', 'cherry']

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

Output:

 1 apple 2 banana 3 cherry 

Ideal when displaying user-friendly numbering (starting from 1 instead of 0).

Method 3: Converting enumerate() to a List or Tuple

You can directly convert the enumerate object to a list or tuple.

fruits = ['apple', 'banana', 'cherry']

# Convert to list of tuples
result = list(enumerate(fruits))

print(result)

Output:

[(0, 'apple'), (1, 'banana'), (2, 'cherry')]

Useful when you need index-value pairs for further processing.

Method 4: Using enumerate() with a String

enumerate() works on any iterable, including strings.

text = "PYTHON"

for index, char in enumerate(text):
print(index, char)

Output:

 0 P 1 Y 2 T 3 H 4 O 5 N 

Helpful for string processing, searching, or formatting tasks.

Method 5: Using enumerate() in List Comprehensions

fruits = ['apple', 'banana', 'cherry']

# Create a list of formatted strings with index
formatted = [f"{i}: {fruit}" for i, fruit 
               in enumerate(fruits, start=1)]

print(formatted)

Output:

['1: apple', '2: banana', '3: cherry']

Clean and compact way to use enumerate in a single line.

Method 6: Enumerate with Conditional Logic

You can combine enumerate() with conditions for more powerful loops.

numbers = [10, 15, 20, 25, 30]

for index, num in enumerate(numbers):
   if num % 20 == 0:
       print(f"Found {num} at index {index}")

Output:

Found 20 at index 2

Great for searching or matching patterns while looping.

Method 7: Using enumerate() with Multiple Lists via zip()

You can combine enumerate() and zip() for complex iterations.

students = ['Alice', 'Bob', 'Charlie']
scores = [85, 90, 95]

for index, (name, score) in enumerate(
              zip(students, scores), start=1):
   print(f"{index}. {name} scored {score}")

Output:

 1. Alice scored 85 2. Bob scored 90 3. Charlie scored 95 

Perfect for reporting, ranking, and combining lists with numbering.

Method 8: Using enumerate() to Modify Lists In-Place

fruits = ['apple', 'banana', 'cherry']

for i, fruit in enumerate(fruits):
fruits[i] = fruit.upper()

print(fruits)

Output:

['APPLE', 'BANANA', 'CHERRY']

Easily modify list elements using their indexes.

Method 9: Using enumerate() Inside a Function

def print_items(items):
   for index, value in enumerate(items, start=1):
       print(f"Item {index}: {value}")

print_items(['Pen', 'Pencil', 'Eraser'])

Output:

 Item 1: Pen Item 2: Pencil Item 3: Eraser 

Makes function output neatly numbered and readable.

Why Use enumerate()?

Eliminates the need for manual index counters like for i in range(len(list))
Increases readability and reduces boilerplate code
Works with any iterable, not just lists
Compatible with unpacking, conditions, and comprehensions

Equivalent Manual Loop (Without enumerate())

fruits = ['apple', 'banana', 'cherry']

# Manual method (not recommended)
for i in range(len(fruits)):
print(i, fruits[i])

Output:

 0 apple 1 banana 2 cherry 

This approach is longer, less readable, and more error-prone.

FAQs — Python enumerate() method (context-rich)

What does Python’s enumerate() do and when should I use it?

enumerate() yields pairs of (index, value) from any iterable. Use it when you need the loop index and the item without managing a separate counter.

fruits = ['a','b','c']
for i, v in enumerate(fruits):
    print(i, v)
# 0 a
# 1 b
# 2 c

What is the exact syntax of enumerate() in Python?

Syntax: enumerate(iterable, start=0). start sets the first index number.

for i, v in enumerate(seq, start=1): ...

How to start enumeration from 1 (use enumerate() with start=1)?

Pass start=1 to enumerate:

for idx, val in enumerate(['x','y'], start=1):
    print(idx, val)
# 1 x
# 2 y

How to use enumerate() with multiple iterables or unpacking?

enumerate() works on a single iterable. Combine with zip() or unpack tuples inside the loop:

pairs = [(1,'a'), (2,'b')]
for i, (num, ch) in enumerate(pairs):
    print(i, num, ch)

For multiple iterables, use zip() then enumerate().

for i, (a,b) in enumerate(zip(list1, list2)): ...

What’s the difference between enumerate() and range(len()) for indexed loops?

enumerate() is cleaner and less error-prone. range(len()) requires indexing into the list and is less Pythonic.

# enumerate (preferred)
for i, v in enumerate(lst): ...

# range(len)
for i in range(len(lst)):
    v = lst[i]

How to get index and value from a dictionary using enumerate()?

Iterating a dict yields keys. Use enumerate(dict) for (index, key), or enumerate(dict.items()) to get (index, (key, value)).

d = {'a':1, 'b':2}
for i, key in enumerate(d):
    print(i, key)

for i, (k, v) in enumerate(d.items()):
    print(i, k, v)

Is enumerate() lazy or memory-efficient (how it behaves with large iterables)?

enumerate() returns an iterator — it’s lazy and memory-efficient. Use it with large or infinite iterables safely.

How to use enumerate() in a list comprehension to build index:value pairs?

You can use it inside comprehensions to create new lists, dicts, etc. Example:

lst = ['a','b']
pairs = [(i, v) for i, v in enumerate(lst)]
idx_map = {v: i for i, v in enumerate(lst)}

How to skip the first N items while keeping correct indices using enumerate()?

Slice the iterable or adjust the start parameter to preserve desired indices:

# skip first 2 but keep original indices
for i, v in enumerate(lst[2:], start=2):
    print(i, v)

Are there common pitfalls when using enumerate() in Python I should avoid?
  • Don’t modify the iterable while enumerating (can cause unexpected behavior).
  • Remember start changes only the reported index, not underlying positions.
  • When enumerating dictionaries, know you get keys unless you use .items().


Referenc: https://docs.python.org/3/library/functions.html#enumerate

Related Post