2

I have a 2D array. While printing I want to remove the trailing spaces at the end of each row.

A = [[ 1,2,3 ,4 ,5],
 [16,17,18,19,6],
 [15,24,25,20,7],
 [14,23,22,21,8],
 [13,12,11,10,9]]

for i in range(len(A)):
    for j in range(len(A)):
        print(A[i][j], end = ' ')
    print()

My test case are failing because of trailing space. Can anyone tell me where the mistake is?

3
  • Thats not valid pyhton. Are you using numpy or something? Please create a minimal reproducible example. This currently only gives you a SyntaxError: invalid syntax Commented Apr 16, 2020 at 17:00
  • your J loop operates on the wrong dimension if you do not have a square input - it should be range(len(A[i]) - or better dont index but use iteration of the data itself Commented Apr 16, 2020 at 17:02
  • 1
    @PatrickArtner modified the code Commented Apr 16, 2020 at 17:07

1 Answer 1

1

You print your spaces yourself by using

print(A[i][j], end= ' ')
               ^^^^^^^^

I would suggest doing

A = [[ 1,2,3 ,4 ,5],
     [16,17,18,19,6],
     [15,24,25,20,7],
     [14,23,22,21,8],
     [13,12,11,10,9]]

for inner in A:
    print(*inner)

Output:

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

without any trailing spaces.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.