0

I have a nested list say:

lst = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]

And I would like the output to be:

new_list = [[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]

this is what i am thinking, but I it is outputting a flat, list of list.

new_lst = []
for i in lst:
  i = list(i)
  for el in i:
    new_list.append([el])
print(new_lst)

I would like to maintain the length of each predefined list in lst

ColeGulledge
  • 393
  • 1
  • 2
  • 12

6 Answers6

2

Try List comprehension [[ [e] for e in l] for l in lst]

Anurag Regmi
  • 629
  • 5
  • 12
1

You could use list comprehension and append every element to another list.

lst = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]
new = [[[numbers] for numbers in elements] for elements in lst]

The above example adjusts for your desired output.

[[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
0

You can use numpy's reshape np.reshape

>>> import numpy as np

>>> lst = np.array([[1,2,3,4], [2,3,4,5], [3,4,5,6]])
>>> lst
array([[1, 2, 3, 4],
       [2, 3, 4, 5],
       [3, 4, 5, 6]])

>>> lst.shape
(3, 4)

>>> lst.reshape(3,4,1)
array([[[1],
        [2],
        [3],
        [4]],

       [[2],
        [3],
        [4],
        [5]],

       [[3],
        [4],
        [5],
        [6]]])

>>> lst.reshape(3,4,1).tolist()
[[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]
imdevskp
  • 2,103
  • 2
  • 9
  • 23
0

Another version, using recursion (you can have more level of depths in your input):

lst = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]


def split(i):
    if isinstance(i, list):
        return [split(v) for v in i]
    else:
        return [i]


print(split(lst))

Prints:

[[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

You could use helper function to have more flexibility later of how you divide the smaller lists. based on an answer from here.

def split_list(alist, wanted_parts=1):
    length = len(alist)
    return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts]
             for i in range(wanted_parts) ]

lst = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]

ret =[]
for mini_list in lst:
    ret.append(split_list(mini_list, len(mini_list)))
Or b
  • 666
  • 1
  • 5
  • 22
0

I think you had the right idea using multiple for loops. This should work:

list = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]

for i in range(0, 3):
     for j in range(0, 4):
          (list[i])[j] = [(list[i])[j]]