-1

I created a list named route in createRoute() and copied the list using list(route) to copyRoute. However, once I change the index route[0][0] in route, it also changes in copyRoute. I can't spot where the error is.

from random import randint

def createRoute():
    route = []
    for horizon in range(8):
        row = []
        for vertical in range(4):
            row.append(randint(0, 50))
        route.append(row)
    return route

def printRoute(list):
    for i in range(8):
        for j in range(4):
            print("%3d" % list[i][j], end=" ")
    print()

def main():
    route = createRoute()
    copyRoute = list(route)
    route[0][0] = 250
    printRoute(route)
    printRoute(copyRoute)

main()
NinjaCoder
  • 58
  • 4
  • 4
    It's a _shallow_ copy, but you need a deep one. See https://docs.python.org/3/library/copy.html#copy.deepcopy – Charles Duffy Oct 28 '22 at 14:30
  • 1
    Take a look at this. https://docs.python.org/3/library/copy.html. You need to deep copy your list. – 0xRyN Oct 28 '22 at 14:31

1 Answers1

1
from random import randint
import copy

def createRoute():
    route = []
    for horizon in range(8):
        row = []
        for vertical in range(4):
            row.append(randint(0, 50))
        route.append(row)
    return route

def printRoute(list):
    for i in range(8):
        for j in range(4):
            print("%3d" % list[i][j], end=" ")
    print()

def main():
    route = createRoute()
    copyRoute = copy.deepcopy(route)
    route[0][0] = 250
    printRoute(route)
    printRoute(copyRoute)

main()

KillerRebooted
  • 470
  • 1
  • 12