Double index function help!


#1

Hello!

I am new to Python and am having a really really hard time with this. I am not able to understand what exactly I have to do and why my code isn’t working.

Create a function named double_index that has two parameters named lst and index .

The function should double the value of the element at index of lst and return the new list with the doubled value.

If index is not a valid index, the function should return the original list.

After writing your function, un-comment the call to the function that we’ve provided for you to test your results.

def double_index (lst, index):
if index >= len(lst):
return lst
double = lst[index] *2
return lst.append(double)

I am new to coding in general, so please I would love some help on this. I’ve been stuck for a really long time on this.


#2
def double_index (lst, index):
  if index >= len(lst):
    return lst
  double = lst[index] *2
  return lst.append(double)

We will want to mutate the list element in place, then return that same list.

lst[index] *= 2
return lst

Note on above compound operator use…

a *= 2

is the same as writing,

a = a * 2

only shorter.


Now we see that there are two return statements which are both the same. We can rewrite the code so there is only the one.

def double_index(lst, index):
    if index < len(lst):
        lst[index] *= 2
    return lst

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.