+ 2

splitting list into evenly size groups

i tried to split list into groups with three elements. i found a code to do it in the web; def chunks(l, chunk_size):     result = []     chunk = []     for item in l:         chunk.append(item)         if len(chunk) == chunk_size:             result.append(chunk)             chunk = []     if chunk:         result.append(chunk)     return result print(chunks([1, 2, 3, 4, 5], 2)) However i could not understand the function of second "chunk=[]" in the 8th row. Can anyone help me to understand? Ty            

29th Oct 2020, 11:10 PM
Hercule Poirot
Hercule Poirot - avatar
4 Antworten
+ 4
result.append(chunk) #adds a chunk to the result chunk = [] # chunk is now an empty list If you were able to figure out the rest of the code then it would be a good exercise to think what would happen if you ommit that line.
29th Oct 2020, 11:27 PM
Kevin ★
+ 4
Not exactly. Let me explain the "for item in l" loop step by step: 1st iteration: # item = 1 chunk.append(item) # adds 1 to the chunk list len(chunk) is 1 and chunk_size is 2 so we ignore the if condition body. 2nd iteration # item = 2 # after appending: chunk = [1, 2] len(chunk) equals chunk_size so the if body runs: result.append(chunk) # now result = [ [1,2] ] chunk = [] # now chunk is an empty list, we already added 1 and 2 to the result and we don't need those values anymore. If we remove that line the chunk will keep growing and we don't want that. The algorithm can be summarized this way: 1- add items to the chunk until the chunk has length "chunk_size" 2- If the chunk has the correct size: 2.1- Add the chunk to the result 2.2- Create a new chunk 3- Start again chunk = [] represents the step 2.2 of the algorithm. Sorry for being late, i missed your reply😅
30th Oct 2020, 9:53 PM
Kevin ★
+ 1
ty kevin. so i suppose by putting an empty list (chunk =[]) at the end of first part of the code, we ensure loop to continue. otherwise it ll stop after the first chunk. am i right?
30th Oct 2020, 4:11 AM
Hercule Poirot
Hercule Poirot - avatar
+ 1
it is really a great explanation. i understand the logic behind it now. ty a lot. 😀
30th Oct 2020, 10:00 PM
Hercule Poirot
Hercule Poirot - avatar