'Nested list creation from a single list with given range [duplicate]
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]]
Solution 1:[1]
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]]
Solution 2:[2]
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)]
Solution 3:[3]
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]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abhyuday Vaish |
| Solution 2 | Bharel |
| Solution 3 | Mechanic Pig |
