0

I was trying to print a simple 2D matrix in Python 3, implementing it with nested lists. So I need something like this:

[ [1, 2, 3],
  [4, 5, 6],
  [7, 8, 8] ]

However, for some reasons the printed output seems to show only the last line.

Here is my code:

# I create a table with 4 rows and 5 columns, all filled by Nones:
table = [[None] * 5] * 4

# Then I initialize it with numbers:
num = 1
for i in range(4):
    for j in range(5):
        table[i][j] = num
        num = num + 1

If now I try to print the table:

for i in range(4):
    for j in range(5):
        print(table[i][j], end="\t")
    print("")

Here is the result:

16      17      18      19      20
16      17      18      19      20
16      17      18      19      20
16      17      18      19      20

However, I expected something like this:

1       2       3       4       5
6       7       8       9       10
11      12      13      14      15
16      17      18      19      20

What's wrong with my code?

Vito Gentile
  • 13,336
  • 9
  • 61
  • 96

1 Answers1

1

The problem with the above code was due to this line:

table = [[None] * 5]  * 4

Indeed, this does not create 20 different "cells". Instead, it creates a list with 5 Nones, and then it replicates the same list 4 times!

In other words, if you try to execute the following code:

print(table[0] == table[1])

you'll get a True, since the rows of the table are actually the same list!

A simple solution to this is to change the initialization approach as follows:

table = [None] * 4

num = 1
for i in range(4):
    table[i] = [None] * 5
    for j in range(5):
        table[i][j] = num
        num = num + 1
Vito Gentile
  • 13,336
  • 9
  • 61
  • 96
  • 1
    Identity is checked via `is`, i.e. `table[0] is table[1]`. Initialization can be done in a list comprehension: `m, n = 4, 5; table = [[i*n + j for j in range(n)] for i in range(m)]`. Anyway, using numpy is probably easier: `table = np.arange(m*n).reshape(m, n)`. By the way, the code you posted will raise a `TypeError` since `None * 5` is not supported: `unsupported operand type(s) for *: 'NoneType' and 'int'`. – a_guest Mar 04 '20 at 15:29