3

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?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Goran
  • 6,644
  • 11
  • 34
  • 54
  • 5
    What criterion do you have for making the new lists? Do you want to break the original into three equal parts? Separate the original every 2 items? What would happen if you had 8 items in `mylist`? – ASGM Jun 08 '13 at 10:10
  • Is the amount of elements in the orignal list arbitrary? – Zacrath Jun 08 '13 at 10:12
  • main list can have unlimited items. Need to create only 3 new lists. First and 4th item need to be in the same list. Also second and 5th, 3rd and 6th like on the example. So first list will look like ` new1=[1,4,7...] – Goran Jun 08 '13 at 10:22

2 Answers2

9

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

Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 1
    @Goran it doesn't. But if you want it to, you need to be more specific in your question about the behavior you're expecting. – ASGM Jun 08 '13 at 10:11
  • I need 3 new lists but main list can have unlimited items. First and 4th item must be in the same list etc as on the example – Goran Jun 08 '13 at 10:12
2

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]])
jamylak
  • 128,818
  • 30
  • 231
  • 230