Table of Contents
In this example, you will learn to split a list into evenly sized chunks in different ways.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 1: Using yield
def split(list_a, chunk_size): for i in range(0, len(list_a), chunk_size): yield list_a[i:i + chunk_size] chunk_size = 2 my_list = [1,2,3,4,5,6,7,8,9] print(list(split(my_list, chunk_size)))
Output
[[1, 2], [3, 4], [5, 6], [7, 8], [9]]
In the above example, we have defined a function to split the list.
- Using a for loop and
range()
method, iterate from 0 to the length of the list with the size of chunk as the step. - Return the chunks using
yield
.list_a[i:i+chunk_size]
gives each chunk. For example, wheni = 0
, the items included in the chunk arei
toi + chunk_size
which is 0 to(0 + 2)th
index. In the next iteration, the items included are 2 to2 + 2 = 4
.
Learn more about yield at Python Generators.
You can do the same thing using list compression as below.
chunk_size = 2 list_chunked = [my_list[i:i + chunk_size] for i in range(0, len(my_list), chunk_size)] print(list_chunked)
Output
[[1, 2], [3, 4], [5, 6], [7, 8], [9]]
Learn more about list comprehension at Python List Comprehension.
2. Example 2: Using numpy
import numpy as np my_list = [1,2,3,4,5,6,7,8,9] print(np.array_split(my_list, 5))
Output
[array([1, 2]), array([3, 4]), array([5, 6]), array([7, 8]), array([9])]
array_split()
is a numpy method that splits a list into equal sized chunks. Here, the size of the chunk is 5.
Note: You need to install numpy on your system.
Related posts:
Python issubclass()
Python Program to Find Sum of Natural Numbers Using Recursion
Python Program to Remove Duplicate Element From a List
Python eval()
Python Set intersection_update()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Removing all Nulls from a List in Java
Python repr()
Python divmod()
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python String partition()
Python Operator Overloading
Python Program to Delete an Element From a Dictionary
Python oct()
Python Program to Create a Long Multiline String
Removing all duplicates from a List in Java
Python property()
Python String replace()
Python Program to Make a Flattened List from Nested List
Python Program to Iterate Over Dictionaries Using for Loop
Python Program to Check if a Number is Positive, Negative or 0
Python Machine Learning - Sebastian Raschka
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Set discard()
Python String format()
Python Program to Convert Kilometers to Miles
Python Program to Solve Quadratic Equation
Python Type Conversion and Type Casting
Python Machine Learning Eqution Reference - Sebastian Raschka
Python sorted()
Remove the First Element from a List