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?

3
  • 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? Commented Jun 8, 2013 at 10:10
  • Is the amount of elements in the orignal list arbitrary? Commented Jun 8, 2013 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...] Commented Jun 8, 2013 at 10:22

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

@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.
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
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]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.