Search code examples
pythonarraysnumpymatrixrow

Replace rows in an MxN matrix with numbers from 1 to N


Im interested in replacing all of my rows in an MxN matrix with values from 1 to N.

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

To: [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]

I've tried using loops going through each row individually but struggle to replace elements.


Solution

  • Try:

    lst = [
        [4, 6, 8, 9, 3],
        [5, 1, 2, 5, 6],
        [1, 9, 4, 5, 7],
        [3, 8, 8, 2, 5],
        [1, 4, 2, 2, 7],
    ]
    
    for row in lst:
        row[:] = range(1, len(row) + 1)
    
    print(lst)
    

    Prints:

    [
        [1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5],
    ]