red_always_mafia
red_always_mafia

Reputation: 189

Issue filling a list with other lists containing random numbers.

I'm trying to print a sort of 2d array using lists of size nxn. The issue I'm having is that the list becomes the final set of random numbers.

For example, if the first set of numbers is [1,5,7] then metaList becomes [[1,5,7],1,2]. But, if the second set of numbers is [3,4,5], then meta list will change to [[3,4,5],[3,4,5],2] The final list is three identical lists, but I'd like them to be different.

I'm sorry if this is something simple. Thanks in advance for any help you can offer. Here is the code.

import random
n = 3

def aBuilder():
    metaList = range(n)
    tempList = range(n)
    for x in range(n):
        metaList[x] = tempList
        print metaList
        for y in range (n):
            tempList[y] = random.randint(1,9)
            print tempList[y]
    return metaList

def printList(List):
    for x in range(n):
        print List[x]

printList(aBuilder())

Upvotes: 0

Views: 52

Answers (1)

timgeb
timgeb

Reputation: 78650

The problem is that metaList only holds references to tempList, so when tempList changes, so will the items in metaList. The solution is to change the line

metaList[x] = tempList

to

metaList[x] = tempList[:]

in order to make a copy of tempList each assignment. A simpler solution for your problem might look like this:

import random
def randlists(n, start, to):
    return [[random.randint(start,to) for i in range(n)] for i in range(n)]

print(randlists(3,1,9))

Upvotes: 3

Related Questions