Pankaj
Pankaj

Reputation: 65

to print a 2-d array (m * n) in python

import numpy as np

a = (['a','b','c',],['d','e','f','g'],['h','i','j','k'])

for row in a:
    print row

for i in range(0,4):
    for j in range(0,4):
        print a[i][j]

I want to print an array where n!=m. My code above I am getting the following error.

Traceback (most recent call last):
  File "/Users/pankajsehgal/mystuff/Python_Practise/2darray", line 10, in <module>
    print a[i][j]
IndexError: list index out of range

I know it is out of range, is there any way to print it. without using numpy.

Upvotes: 0

Views: 175

Answers (1)

Frank
Frank

Reputation: 1285

import numpy as np

a = (['a','b','c',],['d','e','f','g'],['h','i','j','k'])

for row in a:
    print row

for i in range(len(a)):
    sublistlen = len(a[i])
    for j in range(0,sublistlen):
        print a[i][j]

Or just:

import numpy as np

a = (['a','b','c',],['d','e','f','g'],['h','i','j','k'])

for row in a:
    print row

for lis in a:
    for item in lis:
        print item

Upvotes: 1

Related Questions