Lists (Advanced) Challenge #4

On this challenge, my solution seems to be working properly however, when I press Check Answer it tells me to " Double the value at position index in lst "
Here’s my solution:

new_list = []

def double_index(lst, index):
  if index >= len(lst):
    return lst
  else:
    for item in lst:
      if lst.index(item) == index:
        doubled_item = item * 2
        new_list.append(doubled_item)
      else:
        new_list.append(item)
    return new_list
    
print(double_index([3, 8, -10, 12], 2))

Solution provided:

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

Is this just an error because I’m not doing it the way they have shown? Or is my code not doing what they’re actually asking it to do

Assignment Link: https://www.codecademy.com/courses/learn-python-3/articles/advanced-python-code-challenges-lists

The new_list is a good idea but consider what might happen if this function is called more than once.

It’s also worth noting that .index can be quite tricky to work with, for example have a look at the outputs you get for (double_index([1, 1, 1, 12], 2) for example.

If you need to double check exactly how list.index operates- https://docs.python.org/3/tutorial/datastructures.html#more-on-lists

1 Like