Table of Contents
Introduction
In this section of python programming, we will divide the list into chunks of given length n and print the values on the screen.
Program
input_list = [ 'The', 'way', 'I', 'see it', 'if', 'you', 'want', 'the', 'rainbow', 'you', 'gotta', 'put up', 'with', 'the', 'rain'] # Function to div into chunks def div_list_chunks(x,n): for i in range(0, len(x), n): yield x[i:i + n] n = int(input("Enter the size of chunk: ")) print(list(div_list_chunks(input_list, n)))
Output
Explanation
In the above python code, we have created a function div_list_chunks() which will divide the list into the chunks of given length and returns the updated list. The x[ i : i + n ] will slice the list into chunk of n length, whereas the yield keyword returns the value at the time it is suspended. The yield keyword has the property to remember the state while the regular function does not hold the state where it left.
0 Comments