-3

So, I've been trying to create a matrix consisting of multiplication tables up to n with python.

my function goes like this:

def multiplicationTable(n):
    tablePrint = []
    tempTable = []
    for s in range(n):
        s += 1
        tempTable.clear()
        for r in range(n):
            r += 1
            tempTable.append(r*s)
        tablePrint.append(tempTable)
#       print(tablePrint)
    return tablePrint

However, the returned list consists of n versions of the nth tempTable. If you remove the comment, you can see that through each iteration, every single instance within tablePrint gets edited. I had a friend explain roughly that lists are not data, but a memory address to a set of data, is this why this doesn't work?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 2
    Python lists are mutable. http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python – Mephy Oct 20 '14 at 12:42

2 Answers2

1

The issue is that you are appending the tempTable object repeatedly to the tablePrint object. Thus, when you modify tempTable, you also modify all instances of that in tablePrint. This is called mutability, in python lists are mutable. Not all data in python is mutable, for example, your approach wold work if tempTable was a string.

To get around this issue for mutable data simply append a copy:

tablePrint.append(tempTable[::])

Here's a little example:

>>> a = [1,2,3]
>>> b = a
>>> a == b
True
>>> a is b
True       #They are the same object, changing a will change b
>>> b = a[::]
>>> a == b
True
>>> a is b 
False      #They are no longer the same object!

The issue you are having is discussed in length here (in a slightly different form)

Community
  • 1
  • 1
wnnmaw
  • 5,444
  • 3
  • 38
  • 63
0

This would be far simpler with either a list comprehension or nested for loops.

def multiplicationTable(n):
    return [[i*j for j in range(1,n+1)] for i in range(1,n+1)]

>>> multiplicationTable(3)
[[1, 2, 3],
 [2, 4, 6],
 [3, 6, 9]]

Using a more step-by-step nested for loop.

def multiplicationTable(n):
    table = []
    for i in range(1,n+1):
        l = []
        for j in range(1,n+1):
            l.append(i*j)
        table.append(l)
    return table

>>> multiplicationTable(3)
[[1, 2, 3],
 [2, 4, 6],
 [3, 6, 9]]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218