JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Splitting a list into chunks in Python

Author:JIYIK Last Updated:2025/05/09 Views:

One of the Python data structures that can contain mixed values ​​or elements in it is called a list. This article will show you various ways to split a list into chunks. You can use any code example that suits your specifications.


Splitting a list into chunks in Python using list comprehensions

We can use list comprehensions to split a Python list into chunks. This is an effective way to encapsulate operations, making the code easier to understand.

The complete example code is as follows.

test_list = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

n = 3

output = [test_list[i : i + n] for i in range(0, len(test_list), n)]
print(output)

Output:

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['10']]

range(0, len(test_list), n)Returns a range of numbers starting from 0 and len(test_list)ending in , with a step size of n. For example, range(0, 10, 3)will return (0, 3, 6, 9).

test_list[i:i + n]Get the chunk of the list istarting at index and i + nending at . The last chunk of the split list is test_list[9], but the computed index test_list[9:12]is not an error and is equal to test_list[9].


itertoolsSplit a list into chunks using the

This method provides a forgenerator that must be iterated using a loop. Generator is an effective way to describe an iterator.

from itertools import zip_longest

test_list = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]


def group_elements(n, iterable, padvalue="x"):
    return zip_longest(*[iter(iterable)] * n, fillvalue=padvalue)


for output in group_elements(3, test_list):
    print(output)

Output:

('1', '2', '3')
('4', '5', '6')
('7', '8', '9')
('10', 'x', 'x')

[iter(iterable)]*nGenerates an iterator and iterates over the list ntimes. Then izip-longesteffectively loops over each iterator by , and since this is a similar iterator, each such call is advanced, resulting in each such zip loop producing a tuple of n objects.


lambdaSplit a list in Python into chunks using the

You can use a basic lambdafunction to split a list into chunks of a certain size or smaller. This function works on the original list and a variable of size N, iterating over all the list items and splitting them into chunks of size N.

The complete sample code is as follows:

test_list = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

x = 3


def final_list(test_list, x):
    return [test_list[i : i + x] for i in range(0, len(test_list), x)]


output = final_list(test_list, x)

print("The Final List is:", output)

Output:

The Final List is: [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['10']]

Split a list into chunks using the lambdaand methods in Pythonislice

lambdaThe get_start function can be isliceused with the get_start function to produce a generator that iterates over a list. isliceThe get_start function creates an iterator that extracts selected items from an iterable. If the start value is non-zero, then elements of the iterable will be skipped before the start value is reached. Then, elements will be returned consecutively unless a step is set higher than the step size, causing elements to be skipped.

The complete sample code is as follows:

from itertools import islice

test_list = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]


def group_elements(lst, chunk_size):
    lst = iter(lst)
    return iter(lambda: tuple(islice(lst, chunk_size)), ())


for new_list in group_elements(test_list, 3):
    print(new_list)

Output:

('1', '2', '3')
('4', '5', '6')
('7', '8', '9')
('10',)

NumPySplit a list into chunks using the method in Python

NumPyThe library can also be used to split a list into chunks of size N. array_split()The function divides an array into nsub-arrays of a specific size.

The complete sample code is as follows:

import numpy

n = numpy.arange(11)

final_list = numpy.array_split(n, 4)
print("The Final List is:", final_list)

arangeThe function sorts the values ​​according to the given parameters, and array_split()the function generates a list/array according to the given parameters.

Output:

The Final List is: [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8]), array([ 9, 10])]

Split a list into chunks using user-defined functions in Python

This method will iterate over the list and produce consecutive chunks of size n, where n refers to the number of splits that need to be performed. In this function a keyword is used yieldwhich allows a function to stop and resume as the values ​​are rotated when the execution is paused. This is an important difference from a normal function. A normal function cannot return to where it left off. When we use yieldthe while statement in a function, then this function is called a generator. A generator produces or returns values ​​and cannot be named as a simple function, but rather it is named as an iterable function, i.e. using loops.

The complete example code is as follows.

test_list = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]


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


n = 3

output = list(split_list(test_list, n))
print(output)

Output:

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['10']]

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Finding a string in a list in Python

Publish Date:2025/05/09 Views:75 Category:Python

This tutorial shows you how to find elements from a Python list that have a specific substring in them. We will use the following list and extract ack the strings that have in it. my_list = [ "Jack" , "Mack" , "Jay" , "Mark" ] for Find elem

Getting list shape in Python

Publish Date:2025/05/09 Views:139 Category:Python

In Python, knowing the shape of a list is very important for working with data structures, especially when it comes to multidimensional or nested lists. This article explores various ways to determine the shape of a list in Python, from sim

Adding multiple elements to a list in Python

Publish Date:2025/05/09 Views:180 Category:Python

List is a mutable data structure in Python. It can contain values ​​of different types. This article will discuss some methods to append single or multiple elements to a Python list. append() Append a single element in a Python list usi

Get the index of the maximum and minimum values in a list in Python

Publish Date:2025/05/09 Views:117 Category:Python

In this tutorial, we will discuss methods to get the index of the maximum and minimum value of a list in Python. max() Get the index of the maximum value in a list using and list.index() functions in Python max() The function gives the maxi

List of numbers from 1 to N in Python

Publish Date:2025/05/09 Views:116 Category:Python

This tutorial will discuss how to create a list of numbers from 1 to some specified number. Create a user-defined function to create a list of numbers from 1 to N This method will take the desired number from the user and for iterate until

Convert List to Pandas DataFrame in Python

Publish Date:2025/05/09 Views:133 Category:Python

This article will show you how to convert items in a list into a Pandas DataFrame. Convert List to Pandas DataFrame in Python DataFrame, in general, is a two-dimensional labeled data structure. Pandas is an open source Python package that i

Sorting a list by another list in Python

Publish Date:2025/05/09 Views:148 Category:Python

Normally, when we sort a list, we do it in ascending or descending order. However, we can sort a list based on the order of another list in Python. We will learn how to sort a given list based on the values ​​in another list in this art

Normalizing a list of numbers in Python

Publish Date:2025/05/09 Views:134 Category:Python

Normalization means converting the given data to another scale. We rescale the data so that it is between two values. Most of the time, the data is rescaled between 0 and 1. We rescale data for different purposes. For example, machine learn

How to create a list of a specific size in Python

Publish Date:2025/05/09 Views:195 Category:Python

Preallocating storage for a list or array is a common practice among programmers when they know the number of elements in advance. Unlike C++ and Java, in Python you must initialize all preallocated storage with some value. Typically, devel

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial