6

If I initialise a python list

x = [[],[],[]]
print(x)

then it returns

[[], [], []]

but if I do the same with a numpy array

x = np.array([np.array([]),np.array([]),np.array([])])
print(x)

then it only returns

[]

How can I make it return a nested empty list as it does for a normal python list?

3 Answers 3

7

It actually does return a nested empty list. For example, try

x = np.array([np.array([]),np.array([]),np.array([])])
>>> array([], shape=(3, 0), dtype=float64)

or

>>> print x.shape
(3, 0)

Don't let the output of print x fool you. These types of outputs merely reflect the (aesthetic) choices of the implementors of __str__ and __repr__. To actually see the exact dimension, you need to use things like .shape.

Sign up to request clarification or add additional context in comments.

Comments

3

To return a nested empty list from a numpy array, you can do:

x.tolist()
[[], [], []]

However, even if it prints only [], the shape is correct:

x.shape
(3, 0)

And you can access any element like a list:

x[0]
array([], dtype=float64)

1 Comment

tolist is a clever idea here.
2

The easiest solution for you is to convert it to a list with tolist

x = np.array([np.array([]),np.array([]),np.array([])])
print(x)
[]

print(x.tolist())
[[], [], []]

1 Comment

tolist is a clever idea here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.