Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing a list into a list of sub-lists [duplicate]

Tags:

python

list

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], ... ] 
like image 711
James Austin Avatar asked Feb 09 '10 19:02

James Austin


People also ask

Does list slicing create a copy?

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.

Can a list be sliced into Sublists Python?

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.

Does list slicing return a new list?

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.


2 Answers

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)] 
like image 45
sth Avatar answered Sep 24 '22 16:09

sth


[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.

like image 174
SilentGhost Avatar answered Sep 25 '22 16:09

SilentGhost