1

I'm trying to print the row and column numbers at the top and left when printing a matrix. For example, I want this:

test = [[7,7,7,7],[7,7,7,7],[7,7,7,7]]

to be shown as

     0 1 2 3
   0 7 7 7 7
   1 7 7 7 7
   2 7 7 7 7

The matrix prints fine with

for x in test:
    print(*x)

I just don't know how to format it correctly so as to show the index numbers. I found the answer here before but, sadly, I seem to have lost the URL to the question.

Yes
  • 11
  • 2

2 Answers2

0

You can use enumerate to provide indices when looping through an iterable:

for idx, x in enumerate(test):
    print(idx, *x)

For the first line you could do this (I hope the formatting turns out correct, can't test it I'm currently on the go):

print(" ", *range(len(test)))

When your matrix contains numbers of variable length, you can look into string formatting to print them as fixed-width strings. Here for example : How do I make a fixed size formatted string in python?

lhk
  • 27,458
  • 30
  • 122
  • 201
  • Yup, this works. I don't know what I'll have to move around to make it work with double-digit numbers but your solution works for single digits perfectly. – Yes Oct 13 '19 at 08:34
  • Oh, good catch. You're right, when the numbers become variable length you need to invest extra effort. You would do this with string formatting, I linked a relevant question. – lhk Oct 13 '19 at 08:38
  • 1
    Just wanna point out one does not need to listify the range to be able to unpack it, i.e. `print(" ", *range(len(test)))` is fine. – McSinyx Oct 13 '19 at 09:00
0

If you can use pandas:

>>> pandas.DataFrame(test)
   0  1  2  3
0  7  7  7  7
1  7  7  7  7
2  7  7  7  7
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
  • Thanks! I saw something similar with Numpy and it works too. It's just that I'm not allowed to use libraries, unfortunately. – Yes Oct 13 '19 at 10:33