below I have some code that "works" but I don't like it and it's definitely not very "pythonic". Bottom line, I have a list of strings that need to be split into separate lists with a length of n. Note that more than likely there will be a leftover amount (i.e. if the length of the list is to be 5 and I have 13 items in a list, then I'll have 2 lists of 5 and one of 3, which is what I want). Curious what others would do to make this nicer and more pythonic?
import math
things = ['cat', 'dog', 'mouse', 'rat', 'bird', 'manatee', 'turkey', 'chicken', 'cow', 'turtle', 'moose', 'monkey', 'rhino']
desired_len_of_list = 5
num_of_lists = math.ceil(len(things)/desired_len_of_list)
things_list = []
for k in range(num_of_lists):
things_list.append(things[k:k+desired_len_of_list])
del things[0:k+(desired_len_of_list-1)]
Printing the results:
for elem in things_list:
print(elem)
gives the following:
['cat', 'dog', 'mouse', 'rat', 'bird']
['manatee', 'turkey', 'chicken', 'cow', 'turtle']
['monkey', 'rhino']