Turning a list into nested lists in python

Possible Duplicate:
How can I turn a list into an array in python?

How can I turn a list such as:

data_list = [0,1,2,3,4,5,6,7,8]

into a list of lists such as:

new_list = [ [0,1,2] , [3,4,5] , [6,7,8] ]

ie I want to group ordered elements in a list and keep them in an ordered list. How can I do this?

Thanks


Solution 1:

This groups each 3 elements in the order they appear:

new_list = [data_list[i:i+3] for i in range(0, len(data_list), 3)]

Give us a better example if it is not what you want.

Solution 2:

This assumes that data_list has a length that is a multiple of three

i=0
new_list=[]
while i<len(data_list):
  new_list.append(data_list[i:i+3])
  i+=3