>>> lst
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
>>> num_of_parts=4
>>> newlst=[lst[i::4] for i in range(num_of_parts)]
>>> newlst
[['A', 'E', 'I'], ['B', 'F', 'J'], ['C', 'G'], ['D', 'H']]
>>>
Edit 1 : adding some explanation and 2nd method that uses the mod operator
list_obj[start:stop:step]
is similar to the method slice(start, stop, step)
. start
indicates from where slicing must start and the slicing stops at stop - 1
. If start
and stop
are ignored, they are replaced by 0
and len(list) - 1
respectively.
Hence start
and stop
are meant to get a sublist/slice of the list and step
gets every step
(every 2nd/3rd etc) element from that sublist/slice.
Here are some examples demonstrating the same:
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst[1:3]
[1, 2]
>>> lst[1:]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst[:3]
[0, 1, 2]
>>> lst[::2]
[0, 2, 4, 6, 8]
>>> lst[::1]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst[1::2]
[1, 3, 5, 7, 9]
>>>
Mod operator method:
>>> lst
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
>>> num_of_parts=4
>>> newlst=[[lst[i] for i in range(len(lst)) if i%4 == j] for j in range(num_of_parts)]
>>> newlst
[['A', 'E', 'I'], ['B', 'F', 'J'], ['C', 'G'], ['D', 'H']]
>>>
Edit 2 : Making the mod operator method more readable we get the following:
>>> lst=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
>>> newlst=[]
>>> for j in range(num_of_parts):
... temp=[]
... for i in range(len(lst)):
... if i%4 == j:
... temp.append(lst[i])
... newlst.append(temp)
...
>>> newlst
[['A', 'E', 'I'], ['B', 'F', 'J'], ['C', 'G'], ['D', 'H']]
>>>