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:
- The function must accept an iterable as its first argument.
- The function must accept an optional integer
startargument, which specifies the initial index. Ifstartis not provided, it should default to 0. - The function must yield tuples, where each tuple contains the current index and the corresponding item from the iterable.
- The indices should increment sequentially starting from the
startvalue. - 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
startvalue 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
startargument 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
enumeratefunction within yourcustom_enumerateimplementation.
Notes
- Remember that Python generators are created using the
yieldkeyword. - 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.