- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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]]
Advertisements