Home > Back-end >  Python: How to print a looping nested list as a Matrix
Python: How to print a looping nested list as a Matrix

Time:12-05

I want to print a matrix of p*p (where p is an input taken from the user).

The matrix should be in a format of [m,n] i.e [[[3,0],[3,1],[3,2],[3,3]],[2,0],[2,1],[2,2],[2,3]]... and so on.

a = int(input())

l1 = []

for i in range(a):
    l1.append([]) 
     
    for j in range(a):
        l1[i] = [j,i]
        

print(l1)

I tried using this code and realized it is wrong, what can I do to achieve the desired output.

CodePudding user response:

# Take input from the user
p = int(input())

# Create an empty list
l1 = []

# Iterate over the range 0 to p
for i in range(p):
    # Create a new empty sublist for each iteration of the outer loop
    l1.append([])

    # Iterate over the range 0 to p
    for j in range(p):
        # Append the values [j, i] to the sublist
        l1[i].append([j, i])

# Print the matrix
print(l1)
  • Related