Search code examples
pythonlistfunctionpython-3.xenumerate

How to make code that's functionally similar to enumerate without actually using enumerate?


I suppose to write a code that prints out the value of a number that occurs twice in the list given, but they don't allow us to use a built in function on python. How would I be able to write it without using enumerate?

def find_second_occurrence(xs,v):
    count = 0
    value = None
    for i, x in enumerate(xs):
        if v == x:
            count += 1
            if count == 2:
                return i
    if (count < 2):
        return value

Solution

  • enumerate(sequence) is pretty much similar to a construct of the form:

    for i in range(len(sequence)):
        # get sequence[i] and return i and sequence[i] for all i's
    

    So, in your code, replacing enumerate altogether could be done by:

    for i in range(len(xs)):
        x = xs[i]             
        if v == x:
            count += 1
            if count == 2:
                return i
    

    Or, without assigning to an x name to temporarily hold the sequence item:

    for i in range(len(xs)):           
        if v == xs[i]:
            count += 1
            if count == 2:
                return i
    

    Creating a little my_enumerate function, is also rather simple:

    def my_enumerate(sequence, start=0):
        for i in range(len(sequence)):
            yield start+i, sequence[i]
    

    start has also been defined as to match that as used in enumerate and gets a default value of 0.

    Rather than yielding values (if this is mystifying to you), you can create a list (generator comprehensions are similar to yielding) comprehension and return that instead:

    def my_enumerate(sequence, start=0):
        return [(start+i, sequence[i]) for i in range(len(sequence))]