Search code examples
pythoninputmatrix

Get 4x4 matrix input in multiple lines in Python


I'm trying to get a 4x4 matrix as a input.

Sample input:

1234
5678
9124
3248

I've declared array 'a' as follows, so that i could insert/get the matrix value by specifying the indices like a[1][3], a[2][1] etc...

a = [[0 for x in xrange(n+1)] for x in xrange(n+1)]

I've having difficulty in handling the input. i.e How to get the 16 elements in four lines, Four elements/line?


Solution

  • For single digit/character inputs you can simply:

    >>> a,b,c,d = str(input('>> '))
    >> 1234
    >>> a
    '1'
    >>> b
    '2'
    >>> c
    '3'
    >>> d
    '4'
    

    This will achieve what you are looking for by asking the user for input 4 times:

    lst =[]
    for i in range(4):
        a,b,c,d= str(input('>> ')
        lst.append([a,b,c,d])