Computer >> Computer tutorials >  >> Programming >> Python

Break a list into chunks of size N in Python


Here we shall have a given user input list and a given break size. And our task is to break the list as per the given size.

Method 1

Here we are applying yield keyword it enables a function where it left off then again it is called, this is the main difference with regular function.

Example Code

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]]

Method 2

Using List comprehension we can solve this problem in one line.

Example Code

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)
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]]