Nested list creation from a single list with given range

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]]

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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]]

Method 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)]

Method 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]]


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x