Rakshith Nt
Rakshith Nt

Reputation: 129

Print a 2-d array , Matrix style with the element indices

I am trying to print:

a[0][0] a[0][1] a[0][2]
a[1][0] a[1][1] a[1][2]
a[2][0] a[2][1] a[2][2]   

My attempt:

for i in range(n):
    for j in range(n):
        print("a[{}][{}]\t".format(i,j),end="")
    print("")
    print("a[{}][{}]\t".format(i,j),end="")

but I am getting the following output:

a[0][0] a[0][1] a[0][2]
a[0][2] a[1][0] a[1][1] a[1][2]
a[1][2] a[2][0] a[2][1] a[2][2]
a[2][2]

Upvotes: 2

Views: 34

Answers (2)

Austin
Austin

Reputation: 26039

Using f-strings, you can do:

n = 3
for i in range(n):
    for j in range(n):
        print(f'a[{i}][{j}]', end='\t')
    print()

# a[0][0] a[0][1] a[0][2]
# a[1][0] a[1][1] a[1][2]                                           
# a[2][0] a[2][1] a[2][2]

Upvotes: 2

Gasanov
Gasanov

Reputation: 3399

Try following:

for i in range(n):
    for j in range(n):
        print("a[{}][{}]\t".format(i,j),end="")
    print("")

which result in:

a[0][0] a[0][1] a[0][2] 
a[1][0] a[1][1] a[1][2] 
a[2][0] a[2][1] a[2][2] 

Upvotes: 2

Related Questions