-1

I have a list li = [1,2,3,4,5,6,7,8,9] How do I form a nested list for a given range? lets say if the range is 3 I want the output as [[1,2,3][4,5,6][7,8,9]]

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
GeekGroot
  • 102
  • 6
  • 4
    3 is the worst example you could possibly choose because now it is not clear if you want 3 sublists or each sublist to have 3 elements. And what should happen if the list is not cleanly partionable? – luk2302 Apr 29 '22 at 12:12
  • Sorry my bad, 3 is the size of the nested list. The list will always be cleanly partionable. – GeekGroot Apr 29 '22 at 12:15

3 Answers3

0

Taken from itertools' recipes:

from itertools import zip_longest
def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
    "Collect data into non-overlapping fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
    # grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
    # grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
    args = [iter(iterable)] * n
    if incomplete == 'fill':
        return zip_longest(*args, fillvalue=fillvalue)
    if incomplete == 'strict':
        return zip(*args, strict=True)
    if incomplete == 'ignore':
        return zip(*args)
    else:
        raise ValueError('Expected fill, strict, or ignore') ```

Running:

>>> li = [1,2,3,4,5,6,7,8,9]
>>> list(grouper(li, 3))
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
Bharel
  • 23,672
  • 5
  • 40
  • 80
0

Here's how you can do it:

li = [1,2,3,4,5,6,7,8,9]
n = 3
new_li = [li[i:i+n] for i in range(0,len(li),n)]

Output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Abhyuday Vaish
  • 2,357
  • 5
  • 11
  • 27
0

List comprehension matches range:

>>> li = [*range(1, 10)]
>>> [li[i:i + 3] for i in range(0, len(lst), 3)]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31