1

It seems that this code wont run due to an 'str' object has no attribute 'append' error and according to the terminal the problems is due to the following line: new_arr[rows*i + j].append(arr[i][j])

I am trying to convert a matrix to a list.

Any help would be appreciated!

def two_d_translate(arr):

    rows = len(arr)
    cols = len(arr[0])
    total_elements = rows * cols
    new_arr = ['0']*total_elements
    #the number of rows in a mat 
    for i in range(len(arr)):
        for j in range(len(arr[0])):
            new_arr[rows*i + j].append(arr[i][j])
      
    return new_arr
3
  • new_arr is a 1-dimensional array of strings, not a 2-dimensional array. Commented Mar 19, 2021 at 19:32
  • new_arr[rows*i + j] is the string '0'. What are you expecting append() to do? Commented Mar 19, 2021 at 19:33
  • you're appending onto a string based on the error, so I would assume you're trying to append to a '0' that is in the list. in fact, new_arr is still a 1D array, so when you access it with one subscript, you're accessing a '0' directly instead of, say, a row of '0's. Commented Mar 19, 2021 at 19:34

2 Answers 2

2

new_arr[rows*i + j] is a string, not a list, you can't append to it.

You don't need to append anything, you just need to replace that element of the list.

new_arr[rows*i + j] = arr[i][j]

But actually there's no need to pre-fill the list and then assign it. You can just append to the list in the loop.

def two_d_translate(arr):
    new_arr = []
    for row in arr:
        for col in row:
            new_arr.append(col)
    return new_arr
Sign up to request clarification or add additional context in comments.

Comments

0

new_arr is allocated with string values instead of 2d array

new_arr = [[] for i in range(total_elements)]

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.