Writing a remove function that removes an item at a certain index and returns that list while returning the original list without the remove item. I am not sure why but when returning the new list and original list, the values are identical.
def remove(my_list, index: int):
new_list = my_list
new_list.remove(new_list[index])
return new_list, my_list
my_list = ['a', 'b', 'c']
print(remove(my_list, 1)
My output is (['a', 'b', 'd'], ['a', 'b', 'd'])
What I am trying to get is (['a', 'b', 'd'], ['a', 'b', 'c', 'd'])
CodePudding user response:
You are altering my_list
as well as new_list
as they are technically the same thing. Try using list.copy
. And as mentioned in the comments using del
instead of list.remove
makes more sense and is more readable:
def remove(my_list, index: int):
new_list = my_list.copy()
del new_list[index]
return new_list, my_list
CodePudding user response:
You can concatenate subsets of the list that exclude the specified index and return that along with the original list:
def remove(my_list, index: int):
return my_list[:index] my_list[index 1:],my_list