1

I want to define a dynamic two-dimensional array in python.

I don't know how many rows my two-dimensional array will have at the start of my program. I would like to define new rows in this 2D array as needed.

As like this code:

array = [][100]
array[0][]  = new array()
array[0][2] = 'hello'

array[1][] = new array()
array[1][3]= 'hello'
4
  • There are no real two-dimensional arrays in Python, but you can have a list of lists. And you don't need to specify the size beforehand. Or are you really talking about Python arrays ? Commented Jul 13, 2011 at 1:00
  • Yes , I want to define Python arrays.Give Me example how to define list of list whit out specify the size beforehand. thanks Commented Jul 13, 2011 at 1:03
  • i want to do this: >>> mat =[][] >>> mat[0] = ['row1','row1','row1'] >>> mat[1] = ['row2','row2'] >>> mat[2]=['row3'] and give value like this: >>> print mat[1][1] row2 Commented Jul 13, 2011 at 1:28
  • I suggest you read a Python tutorial first (docs.python.org/tutorial). Understanding the basic data types is essential. Commented Jul 13, 2011 at 7:34

2 Answers 2

6

Do you mean something like the following?

class DynamicList(list):

    def __getslice__(self, i, j):
        return self.__getitem__(slice(i, j))
    def __setslice__(self, i, j, seq):
        return self.__setitem__(slice(i, j), seq)
    def __delslice__(self, i, j):
        return self.__delitem__(slice(i, j))

    def _resize(self, index):
        n = len(self)
        if isinstance(index, slice):
            m = max(abs(index.start), abs(index.stop))
        else:
            m = index + 1
        if m > n:
            self.extend([self.__class__() for i in range(m - n)])

    def __getitem__(self, index):
        self._resize(index)
        return list.__getitem__(self, index)

    def __setitem__(self, index, item):
        self._resize(index)
        if isinstance(item, list):
            item = self.__class__(item)
        list.__setitem__(self, index, item)

>>> mat = DynamicList()
>>> mat[0] = ['row1','row1','row1']
>>> mat[1] = ['row2','row2']
>>> mat[2]= ['row3']
>>> mat
[['row1', 'row1', 'row1'], ['row2', 'row2'], ['row3']]
>>> print mat[1][1]
row2
>>> mat[5][5] = 'row5'
>>> mat
[['row1', 'row1', 'row1'], ['row2', 'row2'], ['row3'], [], [], [[], [], [], [], 
[], 'row5']]
>>> print mat[5]
[[], [], [], [], [], 'row5']
>>> print mat[5][5]
row5
Sign up to request clarification or add additional context in comments.

Comments

4

How about using NumPy's matrix class?

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.