0

If I have a list as:

x = [1,2,3,4,5,6,7,8,9,10]

Is there a function or package that lets you specify the length of the combinations you're interested in without losing the remaining elements of the list?

For example, if I was interested in all combinations of length 4, could I return something like:

[[1,2,3,4],[5,6,7,8],[9,10]]
[[1,2,3,4],[5,6,7,8],[9],[10]]

I have been using itertools.combination to get the first list, which is great, but I'm looking for a way to keep the remaining list information into account.

NOTE: I'm not looking for anyone to write code for me to solve it if that's what's required. I'm just asking in case someone knows of a similar function that might help.

user6142489
  • 512
  • 2
  • 10
  • 28

2 Answers2

3

You can use the get_chunks(iterable_obj, chunk_size) function of the third-party open-source library utilspie to achieve this as:

>>> from utilspie import iterutils
>>> x = [1,2,3,4,5,6,7,8,9,10]

#    v type-cast it to `list` as `get_chunks` returns the generator object
>>> list(iterutils.get_chunks(x, 4))
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]

utilspie is available on pip, and to install do:

# For Python 2.x
pip install utilspie

# For python 3.x
pip3 install utilspie

Disclaimer: I am the creator of this library: https://github.com/moin18/utilspie

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1

You can use more-itertools and its sliced() function, as well.

>>> import more_itertools
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(more_itertools.sliced(x, 4))
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
adder
  • 3,512
  • 1
  • 16
  • 28