So I understand how the answer I gave for the question changes the original list.
def double_index(lst, index):
if index >= len(lst):
return lst
else:
lst[index] = lst[index] * 2
return lst
And I understand how the given answer writes the values to a new list instead of changing the original list:
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
What I don’t understand, though, is why this alternate function I came up with changes the original list, even though I specify that the value is written to the new list.
def double_index(lst, index):
if index >= len(lst):
return lst
else:
new_lst = lst
new_lst[index] = lst[index] * 2
return lst
print(double_index([3, 8, -10, 12], 3))
If I return lst or new_lst in the last function, they output the same answer. Is it because, when I assign lst to new_lst, calling new_lst still directs us to the original list? I thought that only the new variable would be altered, not the old one.