Advanced Python Code Challenges - Lists - Double_Index Question

Hi all,

I am working through the above code challenge. and I feel like I’ve satisfied the requirements.

This code passes through and returns the results I want (although the 3 and 8 are in those pesky brackets and I don’t know how to change that). I thought I accounted for the valid index question with the “if” statement, because when I put a 5 in the index, it just returns the original list. But when I click “check answer,” it asks me to make sure I tell it what to do when the index is too big. I’ve pasted my code below with both a valid and an invalid index.

Thanks for your help!

def double_index(lst, index):
    if index > len(lst):
      return lst
    else:
      pass 
    new_index = lst[index]*2
    new_list = [lst[:2], new_index, lst[-1]]
    return new_list
print(double_index([3, 8, -10, 12], 2))
Output
[[3, 8], -20, 12]
def double_index(lst, index):
    if index > len(lst):
      return lst
    else:
      pass 
    new_index = lst[index]*2
    new_list = [lst[:2], new_index, lst[-1]]
    return new_list
print(double_index([3, 8, -10, 12], 5))
Output
[3, 8, -10, 12]
2 Likes

Hello @sister. The reason it is giving you this error is that the last index of a list is actually len(lst) - 1. This is due to the list indexing starting at 0. Whereas len() counting from one:

[1, 2, 3]
#Has a length of three
#The last index is 2.

You therefore might want to change you if statement to accommodate this.
I hope this helps!

2 Likes

I’ll also add that a useful technique for troubleshooting this is drawing it up in two columns on paper (code on one side and the developing variables on the other side) just to check all the logic.

You can double check each step by putting print statements that you just comment out as you go along.

The added benefit of this is that you quickly start picking up good habits so you have to trouble shoot less for small stuff.

2 Likes