3

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"

I have simplified my code to make it easy to understand:

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

Thanks

4
  • 1
    Can you add your expected output please Commented Oct 11, 2016 at 13:37
  • Value of b is [] so, b[i] = empty you can't access to b[i][j], you need to do b[i] = [] and after b[i][j] = a[i][j] Commented Oct 11, 2016 at 13:39
  • @ArnaudWurmel Now I am getting error "IndexError: list assignment index out of range: Commented Oct 11, 2016 at 13:42
  • 1
    What is the purpose of comparing if a[0][0] == 'a' each time in loop? Or is that simplification for us? Commented Oct 11, 2016 at 13:46

3 Answers 3

1

At b[i][j] 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.

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.

The following example makes use of the enumerate 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 IndexError. You can still safely use a[i][j], because the indices are derived from a.

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)

One last comment: it is not recommended to change a list while looping over it in Python (like in the if 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, for you explanation. It was very helpful.
1

Simple, you initialised b to [], so any attempt to access it by index will be out of range. Lists in Python can increase in size dynamically, but this isn't how you do it. You need .append

Comments

1

I don't have any idea about your expected output. I just fixed the error. At first append an empty list to b then you can access b[i] and so on.

Code:

a = [
    ['a', 'b'],
    ['c', 'd']
]
print(a)

b = []
for i in range(len(a)):
    b.append([]) #Append an empty list to `b`
    for j in range(len(a[i])):
        if a[0][0] == 'a':
            a[0][0] = 'b'
        else:
            b[i].append(a[i][j]) #No error now

print(b)

1 Comment

Thanks for your answer. It was very smart.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.