Turning a list into nested lists in python

49,712

Solution 1

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

Solution 2

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 3

Something like:

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

Solution 4

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)

Solution 5

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

List comprehensions for the win :)

Share:
49,712
Double AA
Author by

Double AA

Updated on May 12, 2021

Comments

  • Double AA
    Double AA about 3 years

    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

  • eat
    eat almost 13 years
    FWIW, this won't be very practical one, when you try to generalize the pattern OP described. Thanks
  • Manny D
    Manny D almost 13 years
    Oh I didn't know if the OP was wondering if embedded lists were possible in Python or if there was a way to convert a list into one.
  • Joe Ferndz
    Joe Ferndz over 3 years
    I fixed the code. lots of errors. However, I am not sure if this solves the problem. downvoting the answer.
  • Sindhukumari P
    Sindhukumari P about 3 years
    @JoeFerndz can i know what you have fixed in this ? have you run the code?
  • Sindhukumari P
    Sindhukumari P about 3 years
    Because I remember writing the working code. What changes have you done?
  • Todd
    Todd over 2 years
    I ran into a similar situation to the above question and your code worked perfect! I've been struggling at the last stage. So glad that I could address this.
  • Nils Mackay
    Nils Mackay about 2 years
    I like this, but it only works when the array has a number of elements that's a multiple of 3, otherwise it will throw a ValueError.