Python Forum
2D Array/List OR using variables in other variable names? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: 2D Array/List OR using variables in other variable names? (/thread-9524.html)



2D Array/List OR using variables in other variable names? - IAMK - Apr-14-2018

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.


RE: 2D Array/List OR using variables in other variable names? - nilamo - Apr-14-2018

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]]



RE: 2D Array/List OR using variables in other variable names? - IAMK - Apr-14-2018

(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.


RE: 2D Array/List OR using variables in other variable names? - nilamo - Apr-16-2018

(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.


RE: 2D Array/List OR using variables in other variable names? - IAMK - Apr-16-2018

(Apr-16-2018, 03:31 PM)nilamo Wrote: Then you're doing something else wrong.
No, I've left [0] empty. It's fine :)