mylist = [10, 20, 30, 40, 50, 60, 70, 80]
def chunks(ls, n):
for i in range(0, len(ls), n):
yield ls[i:i + n]
n = 3
result = list(chunks(mylist, n))
print(result)
Output
[[10, 20, 30], [40, 50, 60], [70, 80]]
The yield keyword can make a function come back where it left off when we call the same function again.
In the above code example, we have created a function named chunks that create the equal parts of a list.
We can also use list comprehension to generate n size chunks list from a given list. It will have the minimum code to create equal-size chunks without using any package.
# define a list
mylist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
# use list comprehension to create n size chunks
n = 2
result = [mylist[i:i + n] for i in range(0, len(mylist), n)]
# print the result
print(result)
Output
[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]
0 Comments