12

After some complex operations, a resultant list is obtained, say list1, which is a list of different arrays.

Following is the list1

In [] : list1
Out [] : 
       [array([ 10.1]),
        array([ 13.26]),
        array([ 11.0 ,  12.5])]

Want to convert this list to simple list of lists and not arrays

Expected list2

      [ [ 10.1],
        [ 13.26],
        [ 11.0 ,  12.5] ]

Please let me know if anything is unclear.

Liza
  • 961
  • 3
  • 19
  • 35
  • Possible duplicate of [Converting NumPy array into Python List structure?](https://stackoverflow.com/questions/1966207/converting-numpy-array-into-python-list-structure) – Om Prakash Jul 30 '17 at 20:32
  • possible duplicate of [https://stackoverflow.com/questions/9721884/convert-2d-numpy-array-into-list-of-lists](https://stackoverflow.com/questions/9721884/convert-2d-numpy-array-into-list-of-lists) – Om Prakash Jul 30 '17 at 20:36

6 Answers6

13

You can use tolist() in a list comprehension:

>>> [l.tolist() for l in list1]
[[0.0], [0.0], [0.0, 0.5], [0.5], [0.5], [0.5, 0.69], [0.69, 0.88], [0.88], [0.88], [0.88], [0.88, 1.0], [1.0, 1.1], [1.1], [1.1], [1.1], [1.1, 1.5], [1.5, 2.0], [2.0], [2.0]]
Vinícius Figueiredo
  • 6,300
  • 3
  • 25
  • 44
7

Just call ndarray.tolist() on each member array.

l = [arr.tolist() for arr in l]

This should be faster than building a NumPy array on the outer level and then calling .tolist().

miradulo
  • 28,857
  • 6
  • 80
  • 93
3

How about a simple list comprehension:

list1 = [list(x) for x in list1]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
2
new_list = list(map(list,old_list))

You can use the map function like above. You can see the result below:

In[12]: new_list = list(map(list,old_list))

In[13]: new_list

Out[13]: 
[[0.0],
 [0.0],
 [0.0, 0.5],
 [0.5],
 [0.5],
 [0.5, 0.68999999999999995],
 [0.68999999999999995, 0.88],
 [0.88],
 [0.88],
 [0.88],
 [0.88, 1.0],
 [1.0, 1.1000000000000001],
 [1.1000000000000001],
 [1.1000000000000001],
 [1.1000000000000001],
 [1.1000000000000001, 1.5],
 [1.5, 2.0],
 [2.0],
 [2.0]]
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
1

Use tolist():

import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]
0

If you have more than 1D list, say 2D or more, you can use this to make all entries in just one list, I found it online but don't remember from whom did I take it xD

dummy = myList.tolist()
flatten = lambda lst: [lst] if type(lst) is int else reduce(add, [flatten(ele) for ele in lst])
points = flatten(dummy)

You will get a list of all points or all entries.

I have tested on this list

[[[3599, 532]], [[5005, 493]], [[4359, 2137]]]

and here is the output

[3599, 532, 5005, 493, 4359, 2137]