below is a small part of a larger program. I wonder why "word_list" changes from [['dog', 'cat'], ['fish', 'lion']] to [[1, 'dog', 'cat'], [2, 'fish', 'lion']]? The whole purpose of the function "add_values_to_nested_list" is to add the values one and two to the "word_list" and then create the "new_list". But I do not want the "word_list" to change and I do not get why it does so?. I am calling another function further down in the program with the argument "word_list" so I want the "word_list" to be intact but also create the "new_list". I have used print() just to show how the word_list changes.
def add_values_to_nested_list(list):
lenght_list = len(list)
a = 0
while a<lenght_list:
list[0+a].insert(0, 1+a)
a +=1
return list
word_list = [['dog', 'cat'], ['fish', 'lion']]
print(word_list)
new_list = add_values_to_nested_list(word_list)
print(new_list)
print(word_list) #Why does the "word_list" change to [[1, 'dog', 'cat'], [2, 'fish', 'lion']], I want it be intact.
Here is the same type of problem but simplified. How do I create the "new_list" but still keep the "original_list" intact to use later on in the program. The print() on lines 8,10,13 are just to show what I mean.
def add_value_to_list(original_list):
new_list = original_list
new_list.append(2)
return new_list
original_list = [1]
print(original_list)
new_list = add_value_to_list(original_list)
print(new_list)
print(original_list)