Vishal
Vishal

Reputation: 15

What is the difference between array([array([]),array([])]) and array([[],[]])?

What is the difference between these two numpy arrays?

array([array([1,2,3]),array([4,5,6])])

and

array([[1,2,3],[4,5,6]])

How can we convert one to other?

Upvotes: 0

Views: 2831

Answers (4)

Joe
Joe

Reputation: 7121

These are just equivalent ways to create an array.

From the doc to np.array:

numpy.array(object, ...

object : array_like

    An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence

What you passed are both correct ways to initialize an array. Your first option is a nested sequence, the second one is a nested list.

.

Upvotes: 0

Jab
Jab

Reputation: 27485

As per the docs

numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)

Parameters: object : array_like

  • An array, any object exposing the array interface, an object whose array method returns an array, or any (nested) sequence.

This means using:

array([array([1,2,3]),array([4,5,6])])

Is just redundant to:

array([[1,2,3],[4,5,6]])

As Numpy accepts nested lists (arrays) and will handle them accordingly.

Upvotes: 0

ben_foster04
ben_foster04

Reputation: 65

The result would be the same, but the standard would normally be:

array([[1,2,3],[4,5,6]])

Upvotes: 0

jpp
jpp

Reputation: 164623

The result is the same. There's no need to convert anything:

A = np.array([np.array([1,2,3]), np.array([4,5,6])])
B = np.array([[1,2,3], [4,5,6]])

assert np.array_equal(A, B)

Upvotes: 5

Related Questions