Split a list every x items in Python

avatar

Borislav Hadzhiev

Last updated: Jun 25, 2022

banner

Check out my new book

Split a list every x items in Python #

To split a list every x items:

  1. Use the range() class to iterate over a range with step X.
  2. On each iteration, return a list slice from the current index until the index + X.
main.py
my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] n = 2 result = [ my_list[idx:idx+n] for idx in range(0, len(my_list), n) ] # 👇️ [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'j']] print(result)

We used the range() class to iterate over a range with a step of N.

main.py
my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] n = 2 # 👇️ [0, 2, 4, 6, 8] print(list(range(0, len(my_list), n)))

The range class is commonly used for looping a specific number of times in for loops and takes the following parameters:

NameDescription
startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)

The indexes in the range are the indexes of the first list item in each nested list.

On each iteration we get a slice that starts at the current index and ends at the current index + N.

The example above uses a list comprehension to iterate over the range.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

You can also use a for loop to achieve the same result.

main.py
my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] n = 2 result = [] for idx in range(0, len(my_list), n): result.append(my_list[idx:idx+n]) # 👇️ [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'j']] print(result)

This for loop is the equivalent of the list comprehension we previously used.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.