0

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']
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Matt_Davis
  • 259
  • 4
  • 16
  • Very nice answer here : https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks – thomask Nov 23 '21 at 18:16
  • I appreciate that, I formulated my answer based on that function. Thank you for your help in that! – Matt_Davis Nov 23 '21 at 18:31

2 Answers2

0

So I believe I may have found a far better solution.


things = ['cat', 'dog', 'mouse', 'rat', 'bird', 'manatee', 'turkey', 'chicken', 'cow', 'turtle', 'moose', 'monkey', 'rhino']

[things[i:i + desired_len] for i in range(0, len(things), desired_len)]
Matt_Davis
  • 259
  • 4
  • 16
-1

Try this:

def splitChunks(l,size):
    returnValue = [] 
    for i, el in enumerate(l,1):   
        returnValue.append(el)
        if i % size == 0: 
            yield returnValue
            returnValue = []
    if returnValue: yield returnValue      

if i % size == 0 checks if i is anything divisible by 5.

This code will yield your result.

Hg0428
  • 316
  • 4
  • 15
  • Thank you for contributing an answer. Would you kindly edit your answer to include an explanation of your code? That will help future readers better understand what is going on, and especially those members of the community who are new to the language and struggling to understand the concepts. – Jeremy Caney Nov 24 '21 at 00:26
  • 1
    @JeremyCaney Oh, sorry. I did add it but I must have accidentally deleted it. I will fix that now – Hg0428 Nov 24 '21 at 01:40