Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Is a multidimensional array ("matrix") the same thing as lists within lists?

I'm trying to understand the differences between what people call matrices and what people call lists within lists.

Are they the same in that, once created, you can do identical things to them (reference elements the same way within them, etc).

Examples:

Making lists within a list:

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

Making a multidimensional array:

np.random.rand(3,2)

Stacking arrays to make a matrix:

Array1 = [1,2,3,4]
Array2 = [5,6,7,8]
CompleteArray = vstack((Array1,Array2))
like image 391
philosonista Avatar asked Jul 13 '26 07:07

philosonista


2 Answers

A list of list is very different from a two-dimensional Numpy array.

  • A list has dynamic size and can hold any type of object, whereas an array has a fixed size and entries of uniform type.
  • In a list of lists, each sublist can have different sizes. An array has fixed dimensions along each axis.
  • An array is stored in a contiguous block of memory, whereas the objects in a list can be stored anywhere on the heap.

Numpy arrays are more restrictive, but offer greater performance and memory efficiency. They also provide convenient functions for vectorised mathematical operations.

Internally, a list is represented as an array of pointers that point to arbitrary Python objects. The array uses exponential over-allocation to achieve linear performance when appending repeatedly at the end of the list. A Numpy array on the other hand is typically represented as a C array of numbers.

(This answer does not cover the special case of Numpy object arrays, which can hold any kind of Python object as well. They are rarely used, since they have the restrictions of Numpy arrays, but don't have the performance advantages.)

like image 174
Sven Marnach Avatar answered Jul 15 '26 21:07

Sven Marnach


They are not the same. Arrays are more memory efficient in python than lists, and there are additional functions that can be performed on arrays thanks the to numpy module that you cannot perform on lists.

For calculations, working with arrays in numpy tends to be a lot faster than using built in list functions.

You can read a bit more into it if you want in the answers to this question.

like image 38
thleo Avatar answered Jul 15 '26 22:07

thleo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!