Double Index Challenge (Will my code fail in any circumstance?)

The code I wrote:

def double_index(lst, index):
    return lst[0:index] + [lst[index]*2] + lst[index + 1:]
  except IndexError:
    return lst

Code Academy Solution:

def double_index(lst, index):
  if index >= len(lst):
    return lst
    new_lst = lst[0:index]
  new_lst = new_lst + lst[index+1:]
  return new_lst

My question is if both pieces of code accomplish the same thing. I’m skeptical about my code because of how much shorter it is. Thank you in advance!

Go to number 4 after clicking that link.

According to python idiomatic, its better to ask for forgiveness (except) then for permission (if). Which would make your solution a better fit

however, I disagree with the slicing used in both solutions. You have the index, so its easy to update an element at an index:

the_list[index] = 'new value'

this might result in one more line of code, but it is easier to read

1 Like