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

How to fetch (pop) N elements from a Python list iteratively while list exhausts?

I have the following Python list with a predefined N:

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

I would like to have a collection of N elements (a list of lists, for example) from the list (if len(l) % !=0 then the last collection could be shorter than N). So something like this:

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

How can I achieve the desired output?
(Actually the order of elements in the output doesn’t matter in my case, just to have all the elements once by the defined number groups)

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

>Solution :

you can use this list comprehension

[l[i:i + N] for i in range(0, len(l), N)]
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