-1

Hi I am a beginner to python and I have an exam tomorrow. I do not know how to do this question. I know that I have to use a nested for loop but, I cannot make it work syntactically. Here is the question, I apologize for any formatting errors.

(list of int, int) -> list of (list of int)

Return a list of lists of elements from 1st, where each sublist is the next num elements from 1st. If the length of 1st is not a multiple of num, the final sublist will have fewer than num elements.

»> make_rows([2. 4, 6, 8, 10, 12],3) #Function call

[[2, 4, 6], [8, 10, 12]] # expected output
Amadan
  • 191,408
  • 23
  • 240
  • 301
Mac
  • 123
  • 4
  • 4
    If you "cannot make it work syntactically", post your code, show us what you have done. There are no telepaths here to fix syntax errors on invisible code. :p – Amadan Dec 09 '13 at 01:43
  • 2
    I believe this has already been asked (and answered) [here](http://stackoverflow.com/q/312443/748858) – mgilson Dec 09 '13 at 01:46

2 Answers2

3

do something like this:

def separate(lst, index):
    new_list = [lst[i:i+index] for i in range(0, len(lst), index)]
    return new_list

it will return like so:

>>> print separate([1,2,3,4,5,6],3)
[[1, 2, 3], [4, 5, 6]]
Serial
  • 7,925
  • 13
  • 52
  • 71
  • thanks for your help, but is there a way to do it with nested loops? – Mac Dec 09 '13 at 01:55
  • Why would you need to use nested loops? – Serial Dec 09 '13 at 01:59
  • Sometimes our prof states explicitly to use nested for loop or a while loop – Mac Dec 09 '13 at 02:07
  • It could be done, you could have an outer loop that goes through list_of_int.length/num_per_row and an inner loop that goes through just num_per_row and appends a popped item from list_of_int (using variable names from my solution). However, it's definitely not the cleanest solution. – davecom Dec 09 '13 at 02:09
2

Here is an extremely verbose solution that's not very Pythonic, but shows in detail the steps one would take without List comprehensions or functional style.

The original poster mentioned for-loops, so I thought he may want an iterative approach.

def make_rows(list_of_int, num_per_row):
    new_list = []
    count = 0
    new_inner_list = []
    for n in list_of_int:
        count += 1
        new_inner_list.append(n)
        if (count == num_per_row):
            new_list.append(new_inner_list)
            new_inner_list = []
            count = 0
    return new_list
davecom
  • 1,499
  • 10
  • 30
  • Thanks! simple solution, however it doesn't work if the elements do not divide evenly into num_per_row – Mac Dec 09 '13 at 02:10
  • You could fix that with an if statement right before the return. It could be if (count != 0): new_list.append(new_inner_list) – davecom Dec 09 '13 at 02:11