Break a list into chunks of size N in Python


In this example, we will learn how to break a list into chunks of size N. We will be using the list() function here. The list() function creates a list object. A list object is a collection which is ordered and changeable.

Break a list into chunks of size N with List Comprehension

The List Comprehension can be used to breal a list into chunks of size N −

Example

A = list() # User input for list size n = int(input("Enter the size of the List")) # User input for number print("Enter the number") for i in range(int(n)): p=int(input("Size=")) A.append(int(p)) print (A) n=int(input("Enter Chunk Size")) my_final = [A[i * n:(i + 1) * n] for i in range((len(A) + n - 1) // n )] print ("List of chunks:",my_final)

Output

Enter the size of the List 6
Enter the number
Size= 23
[23]
Size= 34
[23, 34]
Size= 12
[23, 34, 12]
Size= 56
[23, 34, 12, 56]
Size= 33
[23, 34, 12, 56, 33]
Size= 22
[23, 34, 12, 56, 33, 22]
Enter Chunk Size 3
List of chunks: [[23, 34, 12], [56, 33, 22]]

Break a list into chunks of size N with yield keyword

We will use the yield keyword to break a list into chunks of size N −

Example

A = list() n = int(input("Enter the size of the List")) print("Enter the number") for i in range(int(n)): p=int(input("Size=")) A.append(int(p)) print (A) deflist_chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n] n = int(input("Enter Chunk Size")) my_list = list(list_chunks(A, n)) print ("List of Chunks",my_list)

Output

Enter the size of the List 6
Enter the number
Size= 12
[12]
Size= 33
[12, 33]
Size= 11
[12, 33, 11]
Size= 56
[12, 33, 11, 56]
Size= 44
[12, 33, 11, 56, 44]
Size= 89
[12, 33, 11, 56, 44, 89]
Enter Chunk Size 3
List of Chunks [[12, 33, 11], [56, 44, 89]]

Updated on: 12-Aug-2022

373 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements