Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Split A Python List Based Off A Number Of Items

This function takes a list and a number of items to group. It returns a list of lists where each sub-list contains the requested number of items.

Code

def split_list(initial_list, split_index):
      return_lists = []
      while initial_list:
          return_lists.append(initial_list[:split_index])
          initial_list = initial_list[split_index:]
      return return_lists


  list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

  new_lists = split_list(list, 2)

  print(new_lists)

Results

[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g']]

Here's a basic way to do it with just a single split of the first items based on the requested number with the rest of the items going into the second list.

Code

def split_list(initial_list, split_index):
      return [
          initial_list[:split_index],
          initial_list[split_index:]
      ]


  list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

  new_lists = split_list(list, 2)

  print(new_lists)

Results

[['a', 'b'], ['c', 'd', 'e', 'f', 'g']]