Search code examples
pythonsteganography

How to fill up a matrix in Python using for loops


How to add zeroes to the end of a list and fill a matrix with it? Currently I have

(1,0,1,1,0)

How to fill up a matrix such that it looks like this:

[[0, 0, 0], 
 [0, 1, 0], 
 [1, 1, 0]]

Solution

  • In your question, you have clearly added the zeroes to the beginning of the matrix rather than the end but whatever.

    To extend a list to one with 9 items with preceeding zeroes:

    list_out = [0]*(9-len(list_in)) + list_in 
    

    to extend a list to one with 9 items with trailing zeroes just reverse the order:

    list_out = list_in + [0]*(9-len(list_in))
    

    We can convert a list with 9 items to a matrix using

    matrix = [li[0:3,li[3:6],li[6:9]
    

    so eg.

    list_in = [1,2,3]
    li = list_in + [0]*(9-len(list_in))
    matrix = [li[0:3],li[3:6],li[6:9]]
    

    gives

    [[1, 2, 3], [0, 0, 0], [0, 0, 0]]