Split List Based Off A Number Of Items In Python
October - 2021
This function takes a list and an index and returns a list of lists with each one containing the number of items
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)
Returns:
[
['a', 'b'],
['c', 'd'],
['e', 'f'],
['g']
]
Here's a basic way to do it with just a single split
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)
Returns:
# [
# ['a', 'b'],
# ['c', 'd', 'e', 'f', 'g']
# ]