Split a list into list of lists based on modulus of index in Python

Question:

I’d like to write elements of lists to alternating files, and figured I would process the list before.

With a list of strings where the order is important, like ordered_favorite_colors =["red", "blue", "green", "hazel"], and variable number of files number_of_files, I’d like to partition the list into multiple lists so that each file can contain my most favorite color remaining. If number_of_files = 1, the result would be [["red", "blue", "green", "hazel"]], if number_of_files = 3 the result would be [["red", "hazel"], ["blue"], ["green"]]

Asked By: aloha_erich

||

Answers:

l = [0, 1, 2, 3, 4, 5, 6]

size = 3
res = [l[i::size] for i in range(size)]
Answered By: kosciej16
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.