I am wanting to produce a number matrix which will result in displaying the numbers in chronological order. For example, if a 3 x 3 matrix is desired, the output would result as such: [[1,2,3],[4,5,6],[7,8,9]]

The first part of my code can produce the initial list. However I am unsure how to append the lists that would continue this matrix.

n = int(input("Give me an integer: "))
list1 = []
i = 1
for i in range(1,n+1):
list1 = list1 +
i = i + 1
print list1

Any help or advice would be greatly appreciated. Thank you!

Recommended Answers

All 2 Replies

Try to generalize this approach:

matrix3x3 = [range(1, 4), range(4, 7), range(7, 10)]
print matrix3x3  # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

One comment first. You have 2 redundant lines in the original code

n = int(input("Give me an integer: "))
list1 = []
##i = 1     ## this line is redundant-the for() loop handles initializing i
for i in range(1,n+1):
     print "i =", i     ## this will show what the for() loop is doing
     list1 = list1 + [i]
     #i = i + 1     ## this line is redundant-the for() loop also handles incrementing
print list1

To do what I think you want, you have to ask the user for the maximum number to count to, and the "grouping number" or whatever you want to call how many numbers to put in one group. You then use a second, nested for loop underneath the one you have to put the "grouping number" of numbers in a list which you append to the original once the inner loop has finished. Hence a list of lists [[1,2,3], [4,5,6]].

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.