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
+ 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
3 Replies

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

 Expert Mod 2.5K+ P: 2,851 Just for fun, here's another version: Expand|Select|Wrap|Line Numbers num = int(raw_input('Gimme an starting int: ')) n = int(raw_input('Matrix size: '))   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.