John John - 3 months ago 6x
Python Question

How to Reorder Python List For Every N Item

I have a list like ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']

How do I reorder it based on every n item (e.g. every 4 items), so that it has the 1st item, then 5th item, then the 9th item, then the 2nd item, then the 6th item, then the 10th item, then the 3rd item, the 7th item, and the 11th item, then the 4th item, the 8th item, and the 12th item. (Yes, I'm sorry for starting to count by 1 instead of 0 in writing that out....)

['a', 'e', 'i', 'b', 'f', 'j', 'c', 'g', 'k']


Using itertools:

>>> import itertools
>>> l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
>>> step = 4
>>> list(itertools.islice(l*step, None, None, step))
['a', 'e', 'i', 'b', 'f', 'j', 'c', 'g', 'k', 'd', 'h']

Note that the list() call is usually not necessary since most things that take a list will also take an iterator object. But it is convenient for displaying the result.