Hello guys. How are you all? I hope you all fine. In this tutorial we will learn about how to split List Into Chunks in Python. so without wasting time lets learn about of this.
How to split List Into Chunks in Python
split List Into Chunks in Python
to split List Into Chunks in Python just Use lambda. By using lambda you can split list into whatever type of chunks you want. So lets learn about of this without wasting time by given below example:
mylist = ['2','4','6','8','10','12','14','16','18','20'] n = 2 final_list= lambda test_list, x: [test_list[i:i+x] for i in range(0, len(test_list), x)] output=final_list(mylist, n) print('The Final List is:', output)
Output :The Final List is: [['2', '4'], ['6', '8'], ['10', '12'], ['14', '16'], ['18', '20']]
How to split List Into Chunks in Python
to split List Into Chunks in Python just Use list comprehension . By using you can list comprehension split list into whatever type of chunks you want. So lets learn about of this without wasting time by given below example:
mylist = ['2','4','6','8','10','12','14','16','18','20'] n=2 output=[mylist[i:i + n] for i in range(0, len(mylist), n)] print(output)
Output :[['2', '4'], ['6', '8'], ['10', '12'], ['14', '16'], ['18', '20']]
split list into chunks python
To split List Into Chunks in Python just Use list comprehension . By using you can list comprehension split list into whatever type of chunks you want. So lets learn about of this without wasting time by given below example:
mylist = ['2','4','6','8','10','12','14','16','18','20'] n=2 output=[mylist[i:i + n] for i in range(0, len(mylist), n)] print(output)
Output :[['2', '4'], ['6', '8'], ['10', '12'], ['14', '16'], ['18', '20']]
Method 1: Use lambda
By using lambda you can split list into whatever type of chunks you want. So lets learn about of this without wasting time by given below example:
mylist = ['2','4','6','8','10','12','14','16','18','20']
n = 2
final_list= lambda test_list, x: [test_list[i:i+x] for i in range(0, len(test_list), x)]
output=final_list(mylist, n)
print('The Final List is:', output)
Output :
The Final List is: [['2', '4'], ['6', '8'], ['10', '12'], ['14', '16'], ['18', '20']]
Method 2: Use list comprehension
By using you can list comprehension split list into whatever type of chunks you want. So lets learn about of this without wasting time by given below example:
mylist = ['2','4','6','8','10','12','14','16','18','20']
n=2
output=[mylist[i:i + n] for i in range(0, len(mylist), n)]
print(output)
Output :
[['2', '4'], ['6', '8'], ['10', '12'], ['14', '16'], ['18', '20']]
Conclusion
It’s all About this Tutorial. Hope all methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you?
Also, Read