0

I am trying to create an array. When the number of rows and columns are not same, an empty [] appears at the end.

I also want it to be displayed in correct matrix form of [m x n]

I am new to using Python language and this is my first question.

I hope to find a solution to the problem.

import random

m = int(input("Rows : "))
n = int(input("Columns : "))
Mat = []
for i in range(0,n):
    Mat.append([])
for i in range(0,m):
    for j in range(0,n):
        Mat[i].append(j)
        Mat[i][j] = 0
        Mat[i][j] = random.randint(1,100)
print(Mat)

Example:

Columns : 2
Rows : 3

Output:

[[7, 49, 61], [47, 2, 40], []]

I need it like this:

[[7, 49, 61],
 [47, 2, 40]]
4
  • 5
    mat = [[random.randint(1, 100) for _ in range(n)] for _ in range(m)] Commented Oct 11, 2019 at 17:08
  • Thnx But what about the shape ! Commented Oct 11, 2019 at 17:12
  • 1
    you are not going to get the same kind of output, for your mat, as a numpy array when you print it out. unless you are using pprint.pprint(mat) or similar to print out mat. Commented Oct 11, 2019 at 17:15
  • In your inner loop, you could just be doing this instead of those three lines Mat[i].append(random.randint(1,100)) but the list comprehension above is much better Commented Oct 11, 2019 at 17:15

1 Answer 1

2

The problem is here, where you specifically add one row for every column the user requests:

for i in range(0,n):
    Mat.append([])

Instead, use the variable for rows:

for i in range(0, m):
    Mat.append([])

There are several places where you are doing extra work, such as setting a value and then immediately destroying it.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you mr Prune
Note that this is a fix for only the immediate problem. The various comments are very good refinements for your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.