Hello all.

I want to craete a empty double dimensional array.
Later i will get the row and column length. But row length varies each time program. But i will be having the lenght of the row. So hoe to write a generic code for creating a empty 2D array and dynamically insert values in it.

ASAP

hoe to write a generic code for creating a empty 2D array and dynamically insert values in it.

>>> arr_2d = [[]]
>>> arr_2d[0].append(0)
>>> arr_2d[0].append(1)
>>> arr_2d.append([3,4,5])
>>> arr_2d
[[0, 1], [3, 4, 5]]
>>>

It might benefit you to create a 2d array class to handle the many different aspects of working with a 2d array.

commented: as dynamic as it gets, good example +11
commented: Great logic! +0

Not sure if I follow this correctly, but you start with a one dimensional list and append other lists to it. For example ...

qq = []
for row in range(3):
    for col in range(3):
        qq.append([row, col])
        
print qq

"""
my output -->
[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
"""

You could use None as a placeholder.

I like using list comprehensions for this kind of task.

>>> cols = 4
>>> rows = 5
>>> array = [[0 for i in range(cols)] for j in range(rows)]
>>> array
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>>

If it is easier to get your head around, you can use a dictionary of lists, with the dictionary key as the row number, each containing x columns. You could also take this one step further and use a dictionary of dictionaries with row and column number as keys.

def populate_array(rows, columns):
   array_dic = {}
   for row in range(1, rows+1):     ## starts with one, not zero
      array_dic[row] = []
      for col in range(0, columns):
         array_dic[row].append('None')     ## initialize to 'None'
   return array_dic
   
if __name__ == "__main__":
   rows = 10
   columns = 5
   ret_dic = populate_array(rows, columns)
   for key in ret_dic.keys():
      print key, ret_dic[key]
      
   ##---  change some value
   row = 3
   col = 1
   ret_dic[row][col] = 'Changed'
   print "\n"
   for key in ret_dic.keys():
      print key, ret_dic[key]

You could also take this one step further and use a dictionary of dictionaries with row and column number as keys.

Brilliant. I really like this idea! Nice!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.