Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
I have a list such as:
L = [1,2,3,4,5,6,7,8]
Let’s say I want to divide this L into 3 parts into something like:
result = [[1,2,3],[4,5,6],[7,8]]
How can I do this without using higher programming methods (ONLY USING SIMPLE PYTHON METHOD)?
You can try something like:
This pulls out slices from the list that are of length
n, wherenis the number that you add toiand is also the step value in yourrange. As @Eric pointed out, this breaks the list into chunks of three, but not three chunks. In order to get it into three chunks, you can do something like:As it sounds like you have certain constraints, this could be written in a
forloop as well (although this actually has more function calls than the one above 🙂 ):