Program to divide the list elements into chunks and print it using Python

by | Mar 15, 2021 | Python Programs

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 to divide the list elements into chunks and print it

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

Program to divide the list elements into chunks and print it 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.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.