Python Lists -> Double Index


#1

https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-lists/lessons/python-functions-lists-cc/exercises/double-index

Why DON’T these work?

#Write your function here
def double_index(lst, index):
if index > len(lst):
lst = lst
else:
lst[index] = lst[index] * 2
return lst
#Uncomment the line below when your function is done
print(double_index([3, 8, -10, 12], 2))


#Write your function here

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

#Uncomment the line below when your function is done
print(double_index([3, 8, -10, 12], 2))


But this does:

#Write your function here
def double_index(lst, index):
if index < len(lst):
lst[index] = lst[index] * 2
return lst

#Uncomment the line below when your function is done
print(double_index([3, 8, -10, 12], 2))


#2
if index >= len(lst):

so you don’t go out of range.

There is a simple cheat

if index in range(len(lst)):
    lst[index] *= 2
return lst

#3

if index >= len(lst):

“So you don’t go out of range.”

But aren’t we checking to see if we are going out of range? So that if it does go out of range, we return lst. If index is equal to the length, don’t we want it to double the index?


#4

Just being greater than length is not enough. There is no index[length], only index[length - 1].

if index >= len(lst)

excludes the last index. I use range in this test since it perfectly matches how we iterate a list with a for loop.

for x in range(len(lst)):
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 

Those would be the indexes of a list with length 10.