Code Challenge #4: Double Index - Changing Original List

Learn Python 3 | Codecademy

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.

This assigns another name to the same list object referred to by lst. There are a few ways to make a copy of a list. One is to use list slicing. Another is the list.copy() method.

3 Likes

If you want proof of what @midlindner has said:

def double_index(lst, index): if index >= len(lst): return lst else: new_lst = lst # I've added this line if new_lst is lst: print("Lists are same object!") else: print("Lists are different object!") new_lst[index] = lst[index] * 2 return lst double_index([3, 8, -10, 12], 3)

:slight_smile:

2 Likes

Thank you, makes sense now!

1 Like