I have list something like mylist = [1,2,3,4,5,6]
now I need to loop over this list and create 3 new lists like this
new1 = [1,4]
new2 = [2,5]
new3 = [3,6]
What is the easiest way to do this?
I have list something like mylist = [1,2,3,4,5,6]
now I need to loop over this list and create 3 new lists like this
new1 = [1,4]
new2 = [2,5]
new3 = [3,6]
What is the easiest way to do this?
Use slicing:
>>> mylist = [1,2,3,4,5,6]
>>> mylist[::3]
[1, 4]
>>> mylist[1::3]
[2, 5]
>>> mylist[2::3]
[3, 6]
>>> lis = range(1,21)
>>> new1, new2, new3 = [lis[i::3] for i in xrange(3)]
>>> new1
[1, 4, 7, 10, 13, 16, 19]
>>> new2
[2, 5, 8, 11, 14, 17, 20]
>>> new3
[3, 6, 9, 12, 15, 18]
A good read in case you're new to slicing: Explain Python's slice notation
Maybe you should be using numpy
>>> import numpy as np
>>> arr = np.array([1,2,3,4,5,6])
>>> arr.reshape((arr.size//3, 3)).T
array([[1, 4],
[2, 5],
[3, 6]])