-1

I'm trying to create a copy of a list and use it inside my function.

import copy
islands=[['a','b','c',],[]]
def transfer(thing):
    new_islands=copy.copy(islands)
    new_islands[0].remove(thing)
    return new_islands
transfer('b')
print(islands)
//output ['a','c']

I have tried other methods of copying such as new_list=old_list[:] and even creating a for loop that appends every element to an empty list, but I still can't get to separate both lists.

Sorry if this has been asked before, but I really couldn't find an answer to my problem.

2 Answers2

1

You need to copy the inner list as well:

islands = [['a','b','c',],[]]

def transfer(thing):  
    new_islands = [islands[0].copy(), islands[1].copy()]
    new_islands[0].remove(thing)
    return new_islands

print(transfer('b'), islands)  # [['a', 'c'], []] [['a', 'b', 'c'], []]

You can also use deepcopy to copy everything inside the list:

from copy import deepcopy

islands = [['a','b','c',],[]]
def transfer(thing):
    new_islands = deepcopy(islands)
    new_islands[0].remove(thing)
    return new_islands
TwistedSim
  • 1,960
  • 9
  • 23
-1

Let's try to make it simpler and avoid copy at all:

islands=[['a','b','c',],[]]
def transfer(islands, thing):
    return islands[0].remove(thing)

transfer(islands, 'b')
print(islands)
//output ['a','c']