Python: list index out of range (Assigning a 2D list to another 2D list)
<p>I am processing a 2D list and want to store the processed 2D list in a new 2D list with same indexes. But, I am getting error "list index out of range"</p>

<p>I have simplified my code to make it easy to understand:</p>

<pre><code>a = [
    ['a', 'b'],
    ['c', 'd']
]
print a

b = []
for i in range(len(a)):
    for j in range(len(a[i])):
        if a[0][0] == 'a':
            a[0][0] = 'b'
        else:
            b[i][j] = a[i][j] #list index out of range
</code></pre>

<p>Thanks</p>

<p>At <code>b[i][j]</code> you try to access the jth element of the ith element. However, b is just an empty list, so the ith element doesn't exist, let alone the jth element of that ith element. </p>

<p>You can fix this by appending the elements to b. But first, a list (row) should be created (appended to b) for each list (row) in a.</p>

<p>The following example makes use of the <code>enumerate</code> function. It returns the index and the element, so if you want you can still do stuff with i and j, but this will prevent you from gaining an <code>IndexError</code>. You can still safely use <code>a[i][j]</code>, because the indices are derived from <code>a</code>.</p>

<pre><code>a = [
    ['a', 'b'],   
    ['c', 'd']
]
b = []
for i, row in enumerate(a):             # loop over each list (row) in a
    b_row = []                          # list (row) which will be added to b
    for j, element in enumerate(row):   # loop over each element in each list (row) in a
        if a[0][0] == 'a':              # Not sure why each the first element of a has to be checked each loop    # Probably a simplification of the operations.
            a[0][0] = 'b'
        else:
            b_row.append(element)        # append the element to the list(row) that will be added to b
    b.append(b_row)                      # When the row is filled, add it to b

print(b)
</code></pre>

<p>One last comment: it is not recommended to change a list while looping over it in Python (like in the <code>if</code> statement). It is better to apply those changes to your output list, which is b. If it is jsut a simplification of the processessing, just ignore this remark.</p>

python arrays list