Hone logo
Hone
Problems

Implement a Custom enumerate Function

Python's built-in enumerate function is a convenient tool for iterating over a sequence while keeping track of the index. This challenge asks you to reimplement this functionality from scratch, understanding the underlying mechanics of how it pairs indices with items.

Problem Description

Your task is to create a Python function named custom_enumerate that mimics the behavior of the built-in enumerate function. This function should take an iterable (like a list, tuple, or string) and an optional start index (defaulting to 0) as input. It should then yield pairs of (index, item) for each element in the iterable.

Key Requirements:

  1. The function must accept an iterable as its first argument.
  2. The function must accept an optional integer start argument, which specifies the initial index. If start is not provided, it should default to 0.
  3. The function must yield tuples, where each tuple contains the current index and the corresponding item from the iterable.
  4. The indices should increment sequentially starting from the start value.
  5. The function should work with any type of Python iterable.

Expected Behavior:

When custom_enumerate(iterable, start) is called, it should behave like enumerate(iterable, start).

Edge Cases to Consider:

  • Empty iterables.
  • Iterables containing various data types.
  • Using a start value other than 0.

Examples

Example 1:

Input: my_list = ['apple', 'banana', 'cherry'], start_index = 1
Output: (1, 'apple'), (2, 'banana'), (3, 'cherry')
Explanation: The function iterates through `my_list`. Starting from index 1, it yields pairs of (index, item): (1, 'apple'), then increments the index to 2 for 'banana', and finally to 3 for 'cherry'.

Example 2:

Input: my_string = "Hi", start_index = 5
Output: (5, 'H'), (6, 'i')
Explanation: For the string "Hi", starting at index 5, it yields (5, 'H') and then (6, 'i').

Example 3:

Input: empty_list = []
Output: (nothing is yielded)
Explanation: An empty iterable should result in no output from the generator.

Constraints

  • The start argument will always be an integer.
  • The input iterable can be of any standard Python iterable type (e.g., list, tuple, string, range, dictionary keys, etc.).
  • The function should be implemented using a generator (i.e., using yield).
  • You are not allowed to use the built-in enumerate function within your custom_enumerate implementation.

Notes

  • Remember that Python generators are created using the yield keyword.
  • Think about how you can iterate through the input iterable and maintain a separate counter for the index.
  • Consider what happens when the iterable is exhausted.
Loading editor...
python