While working with Lists in Python, you might have come across a problem wherein you need to split the list into some similar-sized chunks. Now, how do you do it? Any idea? Don’t worry, if you answered in the negative. Because here I come with solutions to this problem. Therefore, let’s not waste any time and deliberate; on how do you split a list into evenly sized chunks, right away.

How do you split a list into evenly sized chunks?

There can be many situations where you are given a list and need to split it at certain indexes; to get multiple lists, or if you want to create a table/matrix with a fixed number of rows and columns; where each row of data can be visualized as a list. So, getting right away with the topic, let’s see some good quality examples and the many different techniques; one by one to complete this objective of ours.

Taking help of List comprehension

While working on simpler tasks, list comprehension comes in quite handy. But, for a larger application, we shall use methods and encapsulate these tasks within methods. This way, we will also be able to implement object-oriented concepts too, in the right way.

So, let’s see one such example to implement list comprehension :

ls = [2, 5, 6, 1, 3, 0, 7, 8, 9, 24, 35, 43, 45, 63, 81, 78]
n = 4
out = [ls[i : i+n] for i in range(0, len(ls), n)]
print(out)

Here’s the output :

[[2, 5, 6, 1], [3, 0, 7, 8], [9, 24, 35, 43], [45, 63, 81, 78]]

So, we see that indeed the list comprehension that we write; does split the list into an evenly sized chunk of 4. Hence, this can be one method that you can implement for your code depending on your requirement and necessity. Now, that we have seen this list comprehension method, let’s move on to the next method.

Using an user-defined method

You can also make use of a method that you can define to iterate over the list, and thereby return consecutive chunks of size n; where n refers to the number depicting the size of the even slice of chunks that is to be made.

So, let’s take an example to deliberate further on this:

ls = [2, 5, 6, 1, 3, 0, 7, 8, 9, 24, 35, 43, 45, 63, 81, 78]

def chunks(ls, n): 
       for i in range(0, len(ls), n): 
              yield ls[i : i+n] 

print(list(chunks(ls, 4)))

Here’s the output for this code :

[[2, 5, 6, 1], [3, 0, 7, 8], [9, 24, 35, 43], [45, 63, 81, 78]]

Applying itertools

When you use the itertools method you return a generator that must be passed through with a for loop.

ls = [2, 5, 6, 1, 3, 0, 7, 8, 9, 76, 191, 24, 35, 43, 45, 63, 81, 78]

from itertools import zip_longest 
def chunks(n, iterable, padvalue=None): 
        return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue)

for c in chunks(3, ls): 
      print(c)

The output that you get :

(2, 5, 6)
(1, 3, 0)
(7, 8, 9)
(76, 191, 24)
(35, 43, 45)
(63, 81, 78)

Want help on looping with Lists in Python??

Implementing islice and lambda functions

A lambda function in Python, when used along with the islice method, gives a generator over which to iterate. What does the islice method, effectively do? It is used to choosily(selectively) print specific values in an iterable.

Let’s take an example to see its implementation:

ls = [2, 5, 6, 1, 3, 0, 7, 8, 9, 24, 35, 43, 45, 63, 81, 78]

from itertools import islice
def chunks(a, size):
    a = iter(a)
    return iter(lambda: tuple(islice(a, size)), ())

for i in chunks(ls, 4):
    print(i) 

Here’s its output:

(2, 5, 6, 1)
(3, 0, 7, 8)
(9, 24, 35, 43)
(45, 63, 81, 78)

Applying a lambda function

You can use a simple lambda function to decompose the data into a specific size and split it into a matrix structure or smaller parts. So, let’s learn this method by taking an example :

ls = [2, 5, 6, 1, 3, 0, 7, 8, 9, 24, 35, 43, 45, 63, 81, 78]

n = 4
chunks = lambda ls, n: [ls[i : i+n] for i in range(0, len(ls), n)]
chunks(ls, n)

Output:

[[2, 5, 6, 1], [3, 0, 7, 8], [9, 24, 35, 43], [45, 63, 81, 78]]

THE GIST OF IT ALL !! ~~>

You have seen an ample number of examples and also implemented various methods to tackle our problem. Thus, by now you have quite greatly understood the various methods; that will help you in splitting a list into evenly sized chunks. You can use any method as you deem fit or like based on your requirement and necessity. If you face any complications you can definitely put them up in the comments section. With that note, until next time, see ya !! Goodbye !! :)~~

** :::::: ** ::))::((~~>>

Categorized in: