Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Average of Each N-length Consecutive Segment in a List - Python
Next article icon

Break a List into Chunks of Size N in Python

Last Updated : 20 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The goal here is to break a list into chunks of a specific size, such as splitting a list into sublists where each sublist contains n elements. For example, given a list [1, 2, 3, 4, 5, 6, 7, 8] and a chunk size of 3, we want to break it into the sublists [[1, 2, 3], [4, 5, 6], [7, 8]]. Let’s explore different approaches to accomplish this.

Using List Comprehension

List comprehension is an efficient method for chunking a list into smaller sublists. This method creates a list of lists, where each inner list represents a chunk of the original list of a given size.

Python
a = [1, 2, 3, 4, 5, 6, 7, 8] n = 3   res = [a[i:i + n] for i in range(0, len(a), n)] print(res)  

Output
[[1, 2, 3], [4, 5, 6], [7, 8]] 

Explanation:

  • range(0, len(a), n) generates starting indices for each chunk, i.e., 0, 3, 6, etc.
  • a[i:i + n] slices the list a starting at index i and ending at i + n (the chunk size).
  • For each index in the range, the list is sliced into chunks of size n.

Using Slicing

This is a straightforward approach using a for loop to iterate over the list and slice it manually into chunks of size n. It’s simple to understand and works well for smaller datasets.

Python
a = [1, 2, 3, 4, 5, 6, 7, 8] n = 3   res = []   for i in range(0, len(a), n):  # Slice list in steps of n     res.append(a[i:i + n])  print(res) 

Output
[[1, 2, 3], [4, 5, 6], [7, 8]] 

Explanation:

  • For loop increments by n, ensuring each slice covers a chunk of size n.
  • Each sliced chunk is appended to the chunks list.

Using itertools.islice

For very large lists, itertools.islice can be a memory-efficient way to create chunks without loading the entire list into memory. It allows you to process the list incrementally.

Python
from itertools import islice  a = [1, 2, 3, 4, 5, 6, 7, 8]   n = 3    it = iter(a)  res = [list(islice(it, n)) for _ in range((len(a) + n - 1) // n)]  print(res) 

Output
[[1, 2, 3], [4, 5, 6], [7, 8]] 

Explanation:

  • iter(a) converts list a into an iterator it for sequential access to elements.
  • islice(it, n) fetches n elements at a time from the iterator it using islice.
  • for _ in range((len(a) + n – 1) // n) iterates the required number of times to generate chunks, ensuring even an incomplete final chunk is included.

Using numpy.array_split

For handling larger or more complex datasets, numpy offers the array_split() function. It automatically handles unequal chunk sizes, making it particularly useful when the list size is not perfectly divisible by n.

Python
import numpy as np a = [1, 2, 3, 4, 5, 6, 7, 8] n = 3  res = np.array_split(a, len(a) // n + (len(a) % n != 0)) res = [list(i) for i in res] print(res) 

Output
[[np.int64(1), np.int64(2), np.int64(3)], [np.int64(4), np.int64(5), np.int64(6)], [np.int64(7), np.int64(8)]] 

Explanation:

  • array_split splits the list into chunks, automatically handling unequal chunk sizes.
  • Each resulting numpy array is converted back into a Python list.


Next Article
Average of Each N-length Consecutive Segment in a List - Python

S

Shantanu Sharma.
Improve
Article Tags :
  • Python
  • Python list-programs
  • python-list
Practice Tags :
  • python
  • python-list

Similar Reads

  • How to Create a List of N-Lists in Python
    In Python, we can have a list of many different kinds, including strings, numbers, and more. Python also allows us to create a nested list, often known as a two-dimensional list, which is a list within a list. Here we will cover different approaches to creating a list of n-lists in Python. The diffe
    3 min read
  • Break a list comprehension Python
    Python's list comprehensions offer a concise and readable way to create lists. While list comprehensions are powerful and expressive, there might be scenarios where you want to include a break statement, similar to how it's used in loops. In this article, we will explore five different methods to in
    2 min read
  • How to split a Python list into evenly sized chunks
    Iteration in Python is repeating a set of statements until a certain condition is met. This is usually done using a for loop or a while loop. There are several ways to split a Python list into evenly sized-chunks. Here are the 5 main methods: Method 1: Using a Loop with List SlicingUse for loop alon
    3 min read
  • How to Split a File into a List in Python
    In this article, we are going to see how to Split a File into a List in Python.  When we want each line of the file to be listed at consecutive positions where each line becomes an element in the file, the splitlines() or rstrip() method is used to split a file into a list. Let's see a few examples
    5 min read
  • Average of Each N-length Consecutive Segment in a List - Python
    The task is to compute the average of each n-length consecutive segment from a given list. For example, if the input list is [1, 2, 3, 4, 5, 6] and n = 2, the output should be [1.5, 2.5, 3.5, 4.5, 5.5]. Let's discuss various ways in this can be achieved. Using List ComprehensionThis method uses list
    3 min read
  • Break a long line into multiple lines in Python
    Break a long line into multiple lines, in Python, is very important sometime for enhancing the readability of the code. Writing a really long line in a single line makes code appear less clean and there are chances one may confuse it to be complex. Example: Breaking a long line of Python code into m
    4 min read
  • Get a list as input from user in Python
    We often encounter a situation when we need to take a number/string as input from the user. In this article, we will see how to take a list as input from the user using Python. Get list as input Using split() MethodThe input() function can be combined with split() to accept multiple elements in a si
    3 min read
  • Python | Group elements on break positions in list
    Many times we have problems involving and revolving around Python grouping. Sometimes, we might have a specific problem in which we require to split and group N element list on missing elements. Let's discuss a way in which this task can be performed. Method : Using itemgetter() + map() + lambda() +
    2 min read
  • How to Get First N Items from a List in Python
    Accessing elements in a list has many types and variations. This article discusses ways to fetch the first N elements of the list. Using List Slicing to Get First N Items from a Python ListThis problem can be performed in 1 line rather than using a loop using the list-slicing functionality provided
    4 min read
  • Extending a list in Python
    In Python, a list is one of the most widely used data structures for storing multiple items in a single variable. Often, we need to extend a list by adding one or more elements, either from another list or other iterable objects. Python provides several ways to achieve this. In this article, we will
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences