-1

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'])

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    `new_list = my_list` does nothing here but make another reference to the same obj. You are still altering `my_list` try `my_list.copy()` – Jab Oct 08 '21 at 22:21
  • 1
    Does this answer your question? [List changes unexpectedly after assignment. Why is this and how can I prevent it?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it) – ddejohn Oct 08 '21 at 22:24
  • 1
    BTW, using `list.remove()` doesn't really make sense here. Use `del new_list[index]` instead. – wjandrea Oct 08 '21 at 22:25
  • Also BTW, welcome to Stack Overflow! Please take the [tour] and read [ask]. – wjandrea Oct 08 '21 at 22:26

2 Answers2

0

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
Jab
  • 26,853
  • 21
  • 75
  • 114
0

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
Alain T.
  • 40,517
  • 4
  • 31
  • 51