Search code examples
pythonarrayspython-2.72d

Can array.array() be used to define a 2d array?


I am new to Python. I am using Python 2.7. I want to creat a 2D array, I know how to do it using a list. But the data is large by using a list. In order to save memory, I want to use array rather than list. This was inspired by the "Use array.array('l') instead of list for the (integer) values" given in the answer to Huge memory usage of loading large dictionaries in memory .

Can this method work for 2D array?


Solution

  • The question you refer to is about dictionaries, not arrays. Anyhow you could do this, which creates a list of arrays of 4 byte integers initialized to zero, which is effectively a 2D array:

    from array import array
    
    width, height = 1000, 1000
    array2d = [array('l', (0 for _ in xrange(width))) for _ in xrange(height)]
    
    array2d[999][999] = 42