What is the simplest and reasonably efficient way to slice a list into a list of the sliced sub-list sections for arbitrary length sub lists?
For example, if our source list is:
input = [1, 2, 3, 4, 5, 6, 7, 8, 9, ... ]
And our sub list length is 3 then we seek:
output = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ... ]
Likewise if our sub list length is 4 then we seek:
output = [ [1, 2, 3, 4], [5, 6, 7, 8], ... ]
Slicing lists does not generate copies of the objects in the list; it just copies the references to them. That is the answer to the question as asked.
Given a list of lists and list of length, the task is to split the list into sublists of given length. Method #1: Using islice to split a list into sublists of given length, is the most elegant way. # into sublists of given length. Method #2: Using zip is another way to split a list into sublists of given length.
With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list.
The documentation of the itertools
module contains the following recipe:
import itertools def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return itertools.izip_longest(fillvalue=fillvalue, *args)
This function returns an iterator of tuples of the desired length:
>>> list(grouper(2, [1,2,3,4,5,6,7])) [(1, 2), (3, 4), (5, 6), (7, None)]
[input[i:i+n] for i in range(0, len(input), n)] # Use xrange in py2k
where n
is the length of a chunk.
Since you don't define what might happen to the final element of the new list when the number of elements in input
is not divisible by n
, I assumed that it's of no importance: with this you'll get last element equal 2 if n
equal 7, for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With