Alex Rivera | Logout

Turning a list into nested lists in python

Asked 2011-07-07T17:47:53.510
43

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?

Edit
Report

1 Answer

4

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

List comprehensions for the win :)

answered 2011-07-07T17:54:37.127

Your Answer