Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading