1
def group(l,size):
    length = len(l)
    new = []
    for i in range(0,length):
        for j in range(i,size):
            new[i].append(l[j])
    print new

The above function group(list, size) that take a list and splits into smaller lists of given size.

I need something like this

input: group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

But the problem with the above code is showing index out of range.what's wrong in code? how to append elements into list of lists?

Cœur
  • 37,241
  • 25
  • 195
  • 267
vr22
  • 57
  • 3
  • 13
  • 1
    How can you append to a non-existent list? – Ignacio Vazquez-Abrams Jun 27 '13 at 06:32
  • new[i] does not exist – Aswin Murugesh Jun 27 '13 at 06:35
  • am new to python.what has to done? – vr22 Jun 27 '13 at 06:38
  • 1
    You're going to need to be very explicit with this question as it could be (and I have) mistaken it for [this very often asked one](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python). Are you 1) After a way to group data in groups of various size, or 2) **After help correcting your posted code** - You may wish to [edit] your question accordingly to state if it is indeed number 2 to avoid potential confusion. – Jon Clements Jun 27 '13 at 06:53

3 Answers3

6

Use slice.

>>> def group(l, size):
...     return [l[i:i+size] for i in range(0, len(l), size)]
... 
>>> group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

try:

def group(l,size):
    length = len(l)
    new = []
    for i in range(0, length/size):
        new.append([])
    for i in range(0,len(new)):
        for j in range(i*size,(i*size)+size):
            new[i].append(l[i+j])
    print new

edit: no, don't do this. use slice like falsetru illustrates.

Community
  • 1
  • 1
Matthew Graves
  • 3,226
  • 1
  • 17
  • 20
-1

rough solution would be this :]

def group(l,size):
    length = len(l)
    newlist = []
    newgroup = []
    j = 0
    for i in range(0,length):
        if(j<size - 1):
            j += 1
            newgroup.append(l[i])
        else:
            j = 0
            newgroup.append(l[i])
            newlist.append(newgroup)
            newgroup = []
    if(newgroup != []):
        newlist.append(newgroup)
    return newlist

print(group([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 3))

result: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]

zinuzoid
  • 337
  • 8
  • 14
  • why -1? I didn't test, but if it yields the given result, it seems a valid solution. (but a quite complicated one) – glglgl Jun 27 '13 at 07:10