Search code snippets, questions, articles...

Create equal size chunks from a list in Python

In this post, we are going to describe how to create equal size chunks of N size lists from a given list.
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)
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

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.

Code Example 2: Using list comprehension

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']]
Was this helpful?
0 Comments