Python: How to print a looping nested list as a Matrix

Question:

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.

Asked By: drowsycoder

||

Answers:

# 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)
Answered By: Dileep
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.