Turning a list into nested lists in python

Question:

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?

Asked By: Double AA

||

Answers:

Do you have any sort of selection criteria from your original list?

Python does allow you to do this:

new_list = []
new_list.append(data_list[:3])
new_list.append(data_list[3:6])
new_list.append(data_list[6:])

print new_list
# Output:  [ [0,1,2] , [3,4,5] , [6,7,8] ]
Answered By: Manny D

Something like:

map (lambda x: data_list[3*x:(x+1)*3], range (3))
Answered By: Hyperboreus

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
Answered By: Graham

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

List comprehensions for the win 🙂

Answered By: ba__friend

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.

Answered By: jsbueno

Based on the answer from Fred Foo, if you’re already using numpy, you may use reshape to get a 2d array without copying the data:

import numpy
new_list = numpy.array(data_list).reshape(-1, 3)
Answered By: CÅ“ur

The following function expands the original context to include any desired list of lists structure:

def gen_list_of_lists(original_list, new_structure):
    assert len(original_list) == sum(new_structure), 
    "The number of elements in the original list and desired structure don't match"
        
    list_of_lists = [[original_list[i + sum(new_structure[:j])] for i in range(new_structure[j])] 
                     for j in range(len(new_structure))]
        
    return list_of_lists

Using the above:

data_list = [0,1,2,3,4,5,6,7,8]
    
new_list = gen_list_of_lists(original_list=data_list, new_structure=[3,3,3])
# The original desired outcome of [[0,1,2], [3,4,5], [6,7,8]]

new_list = gen_list_of_lists(original_list=data_list, new_structure=[2,3,3,1])
# [[0, 1], [2, 3, 4], [5, 6, 7], [8]]
Answered By: user12446118

The below one is more optimized and quite straightforward.

data_list = [0,1,2,3,4,5,6,7,8]
result =[]
i=0
while i <(len(data_list)-2):
    result.append(data_list[i:i+3])
    i+=3
print(result)

**output**

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

Answered By: Sindhukumari P

Here is a generalized solution

import math

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

n_batches=math.ceil(len(data_list)/batch_size)

[data_list[x*batch_size:min(x*batch_size+batch_size,len(data_list))] 
    for x in range(n_batches)]

It works even if the last sublist is not the same size as the rest (<batch_size)

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.