Search code examples
pythonlistcollections

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)


Solution

  • you can use this list comprehension

    [l[i:i + N] for i in range(0, len(l), N)]