By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,095 Members | 1,658 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,095 IT Pros & Developers. It's quick & easy.

Help with Appending Number Matrix

P: 4
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 = i + 1
print list1

Any help or advice would be greatly appreciated. Thank you!
Mar 17 '08 #1
Share this Question
Share on Google+
3 Replies


jlm699
100+
P: 314
It would behoove you to use append() to add elements to your list.
Expand|Select|Wrap|Line Numbers
  1. list1.append(i) 
As far as adding lists to a list you can the following:
Expand|Select|Wrap|Line Numbers
  1. >>> olist = ilist = []
  2. >>> for i in range(1,10,3):
  3. ...     ilist = []
  4. ...     for j in range(i, i+3):
  5. ...         ilist.append(j)
  6. ...     olist.append(ilist)
  7. ...     
  8. >>> olist
  9. [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  10. >>> 
So to fit your code it would look like this:
Expand|Select|Wrap|Line Numbers
  1. n = int(raw_input('Gimme an int: '))
  2.  
  3. olist = ilist = []
  4. for i in range(1, n * n + 1, n):
  5.     ilist = []
  6.     for j in range(i, i + n):
  7.         ilist.append(j)
  8.     olist.append(ilist)
  9.  
  10. print 'Results:',olist
Mar 17 '08 #2

bvdet
Expert Mod 2.5K+
P: 2,851
Just for fun, here's another version:
Expand|Select|Wrap|Line Numbers
  1. num = int(raw_input('Gimme an starting int: '))
  2. n = int(raw_input('Matrix size: '))
  3.  
  4. print [[i+j for i in range(num,num+n)] for j in range(0,n*n,n)]
Starting number = 17, size =8:
[[17, 18, 19, 20], [21, 22, 23, 24], [25, 26, 27, 28], [29, 30, 31, 32]]
Mar 17 '08 #3

P: 4
Thank you!

So, 2 empty lists allow me to store the lists being generated by the first for loop.
Mar 17 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.