0

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())
red_always_mafia
  • 179
  • 2
  • 10
  • Because you're filling `metaList` with **references to the same list object** and modifying it. – jonrsharpe Jul 02 '14 at 14:41
  • @jonrsharpe I was about to answer where the problem is and give a simpler function. I don't exactly see why this is a duplicate of a question involving dictionaries? – timgeb Jul 02 '14 at 14:42
  • @timgeb I have reopened, but the problem is identical - filling a list with references to a mutable container – jonrsharpe Jul 02 '14 at 14:43
  • Oh, ok, I see your reason for closing it now. – timgeb Jul 02 '14 at 14:47

1 Answers1

3

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))
timgeb
  • 76,762
  • 20
  • 123
  • 145