Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print 3x3 array in python?

Tags:

python

I need to print a 3 x 3 array for a game called TicTackToe.py. I know we can print stuff from a list in a horizontal or vertical way by using

listA=['a','b','c','d','e','f','g','h','i','j']
# VERTICAL PRINTING 
for item in listA:
        print item

Output:

a
b
c

or

# HORIZONTAL  PRINTING
for item in listA:
        print item,

Output:

a b c d e f g h i j

How can I print a mix of both, e.g. printing a 3x3 box like

a b c
d e f
g h i
like image 339
Smple_V Avatar asked Mar 09 '16 22:03

Smple_V


1 Answers

You can enumerate the items, and print a newline only every third item:

for index, item in enumerate('abcdefghij', start=1):
    print item,
    if not index % 3:
        print

Output:

a b c
d e f
g h i
j

enumerate starts counting from zero by default, so I set start=1.

As @arekolek comments, if you're using Python 3, or have imported the print function from the future for Python 2, you can specify the line ending all in one go, instead of the two steps above:

for index, item in enumerate('abcdefghij', start=1):
    print(item, end=' ' if index % 3 else '\n')
like image 144
Peter Wood Avatar answered Oct 13 '22 00:10

Peter Wood