[SOLVED] Where am I going wrong with enumerate?

Issue

I know the answer is probably super simple, but I’m absolutely stuck on this short piece of code. The function has no effect on the input list when I run it.

def squareEven(array):
    for idx, val in enumerate(array):

        if idx % 2 == 0:
            val = val * val
        else:
            val = val

    return array

array = [1, 2, 4, 9, 20]

print(squareEven(array))

Solution

Here are two ways, one bad, one good:

def squareEven(array):
    for idx in range(len(array)):
        if idx % 2 == 0:
            array[idx] = array[idx] * array[idx]
    return array

array = [1, 2, 4, 9, 20]
print(squareEven(array))

This is better, because it doesn’t damage the original array as a side effect:

def squareEven(array):
    new = []
    for idx,val in enumerate(array):
        if idx % 2 == 0:
            new.append(val * val)
        else:
            new.append(val)
    return new

array = [1, 2, 4, 9, 20]

print(squareEven(array))

Answered By – Tim Roberts

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.