Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is list() not creating a new list

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()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading