Break a list into chunks of size N in Python

Break a list into chunks of size N in Python

  • The yield keyword enables a function to comeback where it left off when it is called again. 
  • This is the critical difference from a regular function. A regular function cannot comes back where it left off. 
  • The yield keyword helps a function to remember its state. 
  • The yield enables a function to suspend and resume while it turns in a value at the time of the suspension of the execution.

Method : 

  • Using Yield

Source Code:

#Follow @Programmerfect

my_list = ['Programmerfect', 'Rahul', 'Richard', 'Neha',
        'Manish','Abhi', 'Anoop', 'Madhu',
            'Anjali','Kira', 'Andro']

# Yield successive n-sized
# chunks from l.
def divide_chunks(l, n):
   
    # looping till length l
    for i in range(0, len(l), n):
        yield l[i:i + n]

# How many elements each
# list should have
n = 5

x = list(divide_chunks(my_list, n))
print (x)  


Comments