2

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))
philosonista
  • 65
  • 2
  • 7
  • 2
    A list within a list doesn't necessarily have to be the same length as another list within the parent list. – childofsoong Nov 30 '16 at 18:37
  • If you have a pure numpy matrix, the row must be the same length and uniform. Otherwise it will be a uniform series of Python objects. – dawg Nov 30 '16 at 18:39
  • Python itself doesn't have arrays or matrices as built in types or in its standard library. Are you referring to NumPy arrays? – das-g Nov 30 '16 at 18:56
  • Yes, I am referring to NumPy arrays. Apologies. I migrated over from Java, where I believe it is built in? – philosonista Dec 01 '16 at 20:54

2 Answers2

7

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.)

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
3

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.

Community
  • 1
  • 1
thleo
  • 742
  • 2
  • 8
  • 21