Search code examples
pythonmatrixappendbehind

In Python is there any way to append behind?


I have a matrix:

[[1 2 3],
[4 5 6], 
[7 8 9]]  

and I need to create a new matrix:

[[7 4 1],
[8 5 2],
[9 6 3]]

I tried

new_matrix = [[1]]
new_matrix.append(matrix[1][0])

and got a new_matrix = [4 1] instead of a new_matrix = [1 4]

If you need more clarification, please just ask.


Solution

  • Yes. Use new_matrix.insert(0,matrix[1][0]).

    insert(position,value) allows you to insert objects into specified positions in a list. In this case, since you want to insert a number at the beginning, the position is zero.

    Note, however, that this take O(n) time if new_matrix has n elements. If new_matrix has 100 elements, it will take ten times longer to add something to the beginning than if it has 10. That's much slower than adding something to the end of the list, which usually takes O(1): it should be fast regardless of how big new_matrix is. See here for more on time complexity of python operations. If you'll regularly be adding elements to the beginning of lists, you might want to think about whether you can reverse what you're doing.

    Also, note that the way you've done things, this will give you a new_matrix of [4,[1]]. I'm not quite sure what you want: if you want the final results as you are describing them, then you need new_matrix = [1]. If your code is correct (new_matrix = [[1]]), and you want [[4,1]], then you'll need to do new_matrix[0].insert(0,4). If you want [[4],[1]], you'll need to do new_matrix.insert(0,[4]), and so on.

    As an aside, since you seem to be doing things with matrices, have you considered using numpy?


    (I'd like to point out that, if this answer seems a bit off-topic, it's because this question was edited to be something entirely different than was originally asked.)

    As for the new question: while Stefan's answer is good python, you may be giving yourself too much work. It's clear you're trying to implement something like a matrix transpose, except mirrored. If you're doing those sorts of manipulations, Numpy is much easier and faster. In this case, with numpy arrays, you'd just need to do the following:

    import numpy as np # import numpy
    matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Here's your matrix
    new_matrix_1 = matrix[::-1,:] # Here's your matrix with all the rows reversed: [[7,8,9],[4,5,6],[1,2,3]]
    new_matrix = new_matrix_1.T # Here's the transpose of that, which is what you want.
    

    While this is just one thing, this will make everything you do easier. For example, arithmetic will actually work: new_matrix+matrix, 2*new_matrix, and so on. You'd have to implement this manually otherwise.