Python 3 - Code challenges - Lists Advanced #4

I am having trouble to understand what is wrong with how i coded this exercise

The answer of the exercise is similar, “looks to me” like it does the same…but when i click on “check answer” it asks me to do something i already did. " Double the value at position index in lst"

I did it like

def double_index(lst, index):
  if index >= len(lst):
    return lst
  else:
    di = lst[0:index] + lst[index+1:]
    di.insert(index, lst[index]*2)
    return di

And the sample answer did it like:

def double_index(lst, index):
  # Checks to see if index is too big
  if index >= len(lst):
    return lst
  else:
    # Gets the original list up to index
    new_lst = lst[0:index]
 # Adds double the value at index to the new list 
  new_lst.append(lst[index]*2)
  #  Adds the rest of the original list
  new_lst = new_lst + lst[index+1:]
  return new_lst

well, I think I saw you answer your own question on that line :grin:
I think they have more checks that happen in the background, like a set of calls that check if it works for every index or just the one that’s called.

yea but even after i corrected that little part it still tells me the same when i click on “check answer” :thinking:

Perhaps you could talk through the logic/flow you use for when you do have a list that should be modified. How do you achieve this?

Adding to what @tgrtim asked, how many tools do we really need for this task? Are we trying to find a use for tools that are not needed?

A function such as this should not be complicated. Only two steps are required:

  • validate the input
  • double the value at the valid index

There is not a lot of logic suggested there, so we can put most of the tools away.

if (valueIsValid) {
    array[index] *= 2;
}

Regardless that the array may have been passed in, it needs no return; but, if there is an assignment to this call, then return the array.

2 Likes

Seemed to work for me, I checked it before I responded.

1 Like

ok so im not crazy then… ill delete it all and re-do it then

Like this?

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

I thought this would work but I guess you’d have to do a try:

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

That doesn’t validate the value as within range. The first example does.

1 Like