Python Forum

Full Version: 2D Array/List OR using variables in other variable names?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to do one of two things:
1- .append() to a 2d array.
OR
2- have multiple arrays, e.g. array1, array2, then use array+intvar.append()

I have tried defining my array (list) with array = [][] and array = [[]].
I have tried appending to array[1].append("test").

I have also tried:
array1 = []
intvar = 1
exec("array"+str(intvar)).append("test"))
Error: AttributeError: 'NoneType' object has no attribute 'append'

Ideally, solution 1 would be better than solution 2, because I don't need to manually create X arrays. However, I would like an explanation for both methods.

Thank you in advance.
A multidimensional array, is just an array of arrays. The error you get, is because you're trying to append an item to the first element of a list that doesn't have any items.
>>> table = []
>>> for row in range(5):
...   table.append([])
...   for col in range(10):
...     table[row].append(col)
...
>>> table
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
>>> import pprint
>>> pprint.pprint(table)
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
(Apr-14-2018, 04:03 PM)nilamo Wrote: [ -> ]A multidimensional array, is just an array of arrays. The error you get, is because you're trying to append an item to the first element of a list that doesn't have any items.
>>> table = [] >>> for row in range(5): ... table.append([])
That makes sense, but when I tried it, I instead wrote for row in range(1, 5): since it can't access row[0].

Now it works. Thank you.
(Apr-14-2018, 10:46 PM)IAMK Wrote: [ -> ]I instead wrote for row in range(1, 5):
Then you're doing something else wrong. What I shared was working code, copied directly from an interactive session. A list with any elements will always have an item at element 0.
(Apr-16-2018, 03:31 PM)nilamo Wrote: [ -> ]Then you're doing something else wrong.
No, I've left [0] empty. It's fine :)