How to allocate array size in Python

arrays, python

Solution

Something along the lines of

In [12]: a = 5

In [13]: b = 7

In [14]: array_ab = [ [ '?' for i in xrange(a) ] for j in xrange(b) ]

In [15]: array_ab
Out[15]:
[['?', '?', '?', '?', '?'],
 ['?', '?', '?', '?', '?'],
 ['?', '?', '?', '?', '?'],
 ['?', '?', '?', '?', '?'],
 ['?', '?', '?', '?', '?'],
 ['?', '?', '?', '?', '?'],
 ['?', '?', '?', '?', '?']]

In [16]: array_ab[4][2] = '1'

In [17]: array_ab
Out[17]:
[['?', '?', '?', '?', '?'],
 ['?', '?', '?', '?', '?'],
 ['?', '?', '?', '?', '?'],
 ['?', '?', '?', '?', '?'],
 ['?', '?', '1', '?', '?'],
 ['?', '?', '?', '?', '?'],
 ['?', '?', '?', '?', '?']]

In particular, you're using list comprehensions and xrange.

Problem

Python newbie here. I've searched quite a bit for a solution to this but nothing quite fits what I need. I would like to allocate an empty array at the start of my program that has a rows and b columns. I came up with a solution but encountered an interesting problem that I didn't expect. Here's what I had: ``` a = 7 b = 5 array_ab = [['?'] * b] * a ``` which produces ``` [['?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?']] ``` However, if I try to change a single element, it treats every row as the same object and effectively changes the entire column to that element. So for example ``` array_ab[4][2] = '1' ``` produces ``` [['?', '?', '1', '?', '?'], ['?', '?', '1', '?', '?'], ['?', '?', '1', '?', '?'], ['?', '?', '1', '?', '?'], ['?', '?', '1', '?', '?'], ['?', '?', '1', '?', '?'], ['?', '?', '1', '?', '?']] ``` Clearly I need a better way to create the blank array than by multiplication. Is there a solution to this in python? (It was so simple in FORTRAN!)

Original source

Related problems