Python – Split Array or List to chunks
Today in this article, we shall see how to perform Python Split Array or List to chunks i.e. evenly sized chunks.
Python has a very simple way of achieving the same.
In fact, there are numerous ways you can achieve this but we shall concentrate on simple basic techniques in this article.
Today in this article, we will cover below aspects,
Command – Python Split Array or List to chunks
[list[i:i+x] for i in range(0, len(list), x)]
Create as Reusable Method
def chunk_list (x): return [list[i:i+x] for i in range(0, len(list), x)]
Example
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,18,19,20] def chunk_list (x): return [list[i:i+x] for i in range(0, len(list), x)] print(chunk_list(5))
Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20]]
Using range to loop and Chunk array
The range
type represents an immutable sequence of numbers on the fly and is commonly used for looping a specific number of times in loops.
The numbers can be used to index into collections such as strings.
Command
- r
ange
(stop)
range
(start, stop[, step])
In the above command
star
t- The value of the start parameter (or 0
if the parameter was not supplied)
stop
– The value of the stop parameter
step
– The value of the step parameter (or 1
if the parameter was not supplied)
Example 1
range(3, 6)
Create a sequence of numbers from 3 to 5, and print each item in the sequence
Output
3
4
5
Example 2
range(5, 25, 5)
Create a sequence of numbers from 5 to 25, but increment by 5
Output
5 10 15 20
That’s all! Happy coding!
Does this help you fix your issue?
Do you have any better solutions or suggestions? Please sound off your comments below.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.