Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 976
Double AA Avatar asked Jul 07 '11 17:07

Double AA


People also ask

How do I convert a list to a nested list in Python?

We can also use the python module names abstract syntax trees or called ast. It has a function named literal_eval which will keep the elements of the given list together and convert it to a new list.

How do I convert a list to multiple lists?

Thus, converting the whole list into a list of lists. Use another list 'res' and a for a loop. Using split() method of Python we extract each element from the list in the form of the list itself and append it to 'res'. Finally, return 'res'.

How do I nest a list?

Correct: <ul> as child of <li> The proper way to make HTML nested list is with the nested <ul> as a child of the <li> to which it belongs. The nested list should be inside of the <li> element of the list in which it is nested.


2 Answers

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.

like image 98
jsbueno Avatar answered Sep 17 '22 21:09

jsbueno


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 
like image 38
Graham Avatar answered Sep 19 '22 21:09

Graham