How to manipulate 2D arrays?
How to initialize a two-dimensional array (list of lists, if not using NumPy) in Python? - Stack Overflow
Are arrays and lists essentially the same?
w3schools lists tutorials; half of the functions they use don't seem to work?
Videos
I can’t wrap my mind around how to work with nested lists (2D arrays) and I have an assignment where I have to use a lot of them. I used W3Schools and Youtube tutorials to learn Python but they didn’t cover it much or at all, and the notes provided by my teacher weren’t that helpful either.
Now I’m truly behind since I learnt Python before and this is the « blind spot » that I missed. Any advice helps.
To initialize a two-dimensional list in Python, use
t = [ [0]*3 for i in range(3)]
But don't use [[v]*n]*n, it is a trap!
>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0]=1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
A pattern that often came up in Python was
bar = []
for item in some_iterable:
bar.append(SOME EXPRESSION)
which helped motivate the introduction of list comprehensions, which convert that snippet to
bar = [SOME_EXPRESSION for item in some_iterable]
which is shorter and sometimes clearer. Usually, you get in the habit of recognizing these and often replacing loops with comprehensions.
Your code follows this pattern twice
twod_list = [] \
for i in range (0, 10): \
new = [] \ can be replaced } this too
for j in range (0, 10): } with a list /
new.append(foo) / comprehension /
twod_list.append(new) /