0
I am learning Python and I came across an exercise that called for the creation of a group() function that would divide the elements of a list into smaller lists according to predetermined size, according to the two examples below:
group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
would result in [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
group([1, 2, 3, 4, 5, 6, 7, 8, 9], 4)
would result in [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
I was able to solve the problem, but I am looking for simpler and more elaborate options than mine, which did not seem good. Could someone please help me? The code I was able to create was as follows::
def group(lista, a):
b = []
x = 0
if len(lista) % a == 0:
for i in range(int(len(lista)/a)):
b.append([])
for c in range(len(b)):
for i in range(a):
b[c].append(lista[x])
x += 1
else:
for i in range(int(len(lista) / a + 1)):
b.append([])
for c in range(int(len(b)-1)):
for i in range(a):
b[c].append(lista[x])
x += 1
for c in range(0, 1):
for i in range(int(len(lista) % a)):
b[-1].append(lista[x])
x += 1
return b