Python: Split List by Number of Elements

When working with lists in Python, there are times when you might need to split a list into smaller chunks based on a specified number of elements. This can be useful for handling large datasets, chunks of data for API calls, or managing data in batches. Python provides a simple and elegant solution to achieve this using the itertools module and list slicing.

All Important Python Functions for Beginners (Complete Cheat Sheet)
All Important Python Functions for Beginners (Complete Cheat Sheet)

Before we dive into the methods, let's understand the basic concept. If you have a list of 10 items and you want to split it into sublists of 3 items each, you'd expect two sublists: [1, 2, 3] and [4, 5, 6] (ignoring the last two items, 7 to 10).

Python Functions Cheat Sheet for Beginners
Python Functions Cheat Sheet for Beginners

Using List Slicing to Split a List

One straightforward way to split a list is by using Python's list slicing. This method is best when you know the exact number of elements to split the list into.

Python list exercises guide
Python list exercises guide

Here's a simple example. Suppose we have a list of numbers from 1 to 20:

numbers = list(range(1, 21))

python variables
python variables

Splitting into Equal Parts

To split this list into three equal parts, you can use list slicing:

split_list = [numbers[i::3] for i in range(3)]

an important python functions chart with the words and numbers on it, including instructions to use them
an important python functions chart with the words and numbers on it, including instructions to use them

In this case, numbers[i::3] creates a new list that starts at index i and takes every 3rd element. The range(3) part generates indices: 0, 1, 2, which create the three sublists.

Splitting Unevenly

If the list doesn't contain an even number of elements, you'll end up with a smaller sublist at the end. Here's how you can handle that:

PYTHON BASICS
PYTHON BASICS

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

In this function, we use a loop to get each 'chunk' of n elements. If there are less than n elements left at the end, they form the last list in the result.

the cover of collection data types in python, with an image of numbers and symbols
the cover of collection data types in python, with an image of numbers and symbols
Python List Methods Everyone Must Know
Python List Methods Everyone Must Know
30-Day Python Learning Plan for Beginners | Complete Python Roadmap to Learn Coding Fast
30-Day Python Learning Plan for Beginners | Complete Python Roadmap to Learn Coding Fast
Python Data Types
Python Data Types
Important Methods in Python Part-II
Important Methods in Python Part-II
Advanced Python Guide
Advanced Python Guide
Python List Methods
Python List Methods
Python list methods every developer should know.
Python list methods every developer should know.
Python Data Structures Cheat Sheet for Beginners (Lists, Tuples, Sets & Dictionaries)
Python Data Structures Cheat Sheet for Beginners (Lists, Tuples, Sets & Dictionaries)

Using Itertools to Split a List Receiving an Iterator

If you're processing large lists and want to avoid creating intermediate lists, you can use itertools.

The itertools.islice function is a tool for slicing from an iterator. It's a generator function that yields elements from the input iterable, starting at the specified start (default is 0) and ending at stop.

Creating an Iterative Process

Here’s how you can use itertools.islice to split a list into sublists:

from itertools import islice numbers = list(range(1, 21)) for i, chunk in enumerate(islice(numbers, 0, None, 3)): print(f"Chunk {i}: {chunk}")

In this case, islice(numbers, 0, None, 3) yields chunks of 3 elements from the numbers list and an iterator named chunk.

Handling Uneven Lists

With larger lists, you might encounter a final sublist that's shorter than the specified chunk size. To handle this, you can add a condition to stop the loop when the last chunk is smaller than the specified size:

from itertools import islice numbers = list(range(1, 21)) for i, chunk in enumerate(islice(numbers, 0, None, 3), start=1): if len(chunk) < 3: break print(f"Chunk {i}: {chunk}")

The start=1 argument in the enumerate function renumbers the chunks starting from 1 instead of 0.

With that, you now know several ways to split a list by the number of elements in Python. The choice between list slicing, creating a function, or using itertools depends on your specific needs and data size. Happy coding!

Related Articles

List Of Fruits And Their Colours Printable List Of Vegetables In Spanish List The First 20 Elements With Their Symbols And Atomic Numbers Inventory Template Word Free Download Free Printable List Of Foods Dogs Can And Cannot Eat Printable List Of Foods Dogs Can Eat List Of Veggies With Pictures List Of Fruits And Vegetables And Their Health Benefits Pdf Fmcg Household Products List Excel Inventory List Template Free Download