OneMoreError
OneMoreError

Reputation: 7728

Merging lists in a row wise manner to generate a 2D array

I have a number of lists, and I want to merge all these lists in a row wise manner to generate a two dimensional array in Python. How do I do that ?

Ex- 
l1=[1,2,3,4]
l2=[5,6,7,8]
l3=[9,10,11,12]
l4=[13,14,15,16]

I want to get a 2D-array like this

m= 1   2   3   4
   5   6   7   8
   9  10  11  12
   13 14  15  16

Upvotes: 0

Views: 722

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122312

Just put them in a list:

m = [l1, l2, l3, l4]

N-dimensional lists in Python are simply nested lists.

Result:

>>> l1=[1,2,3,4]
>>> l2=[5,6,7,8]
>>> l3=[9,10,11,12]
>>> l4=[13,14,15,16]
>>> m = [l1, l2, l3, l4]
>>> pprint(m)
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

You then access items by row and column with two indexing operations:

>>> print m[1][3]
8

Upvotes: 4

Related Questions