Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

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.

python
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 start

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.

python
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 start