hlame_mastar
hlame_mastar

Reputation: 27

what the differences between ndarray and list in python?

last week, my teacher asks us: when storing integers from one to one hundred, what the differences between using list and using ndarray. I never use numpy before, so I search this question on the website. But all my search result told me, they just have dimension difference. Ndarray can store N dimension data, while list storge one. That doesn't satisfy me. Is it really simple, just my overthinking, Or I didn't find the right keyword to search? I need help.

Upvotes: -1

Views: 450

Answers (2)

Toothpick Anemone
Toothpick Anemone

Reputation: 4644

A one-dimensional array is like one row graph paper .##

enter image description here

You can store one thing inside of each box

PHOTO OF A SECOND EXAMPLE OF A ONE DIMENTIONAL ARRAY

The following picture is an example of a 2-dimensional array

TWO DIMENSIONAL ARRAY

Two-dimensional arrays have rows and columns

I should have changed the numbers.
When I was drawing the picture I just copied the first row many times.
The numbers can be completely different on each row.

import numpy as np

lol = [[1, 2, 3], [4, 5, 6]]
# `lol` is a list of lists

arr_har = np.array(lol, np.int32)

print(type(arr_har)) # <class 'numpy.ndarray'>

print("BEFORE:")
print(arr_har)

# change the value in row 0 and column 2.
arr_har[0][2] = 999

print("\n\nAFTER arr_har[0][2] = 999:")
print(arr_har)

The following picture is an example of a 3-dimensional array

THREE_DIMENSIONAL_ARRAY

Summary/Conclusion:

A list in Python acts like a one-dimensional array.

ndarray is an abbreviation of "n-dimensional array" or "multi-dimensional array"

The difference between a Python list and an ndarray, is that an ndarray has 2 or more dimensions

enter image description here

Upvotes: 2

Fabian Andres
Fabian Andres

Reputation: 36

There are several differences:

-You can append elements to a list, but you can't change the size of a ´numpy.ndarray´ without making a full copy.

-Lists can containt about everything, in numpy arrays all the elements must have the same type.

-In practice, numpy arrays are faster for vectorial functions than mapping functions to lists.

-I think than modification times is not an issue, but iteration over the elements is. Numpy arrays have many array related methods (´argmin´, ´min´, ´sort´, etc).

I prefer to use numpy arrays when I need to do some mathematical operations (sum, average, array multiplication, etc) and list when I need to iterate in 'items' (strings, files, etc).

Upvotes: 2

Related Questions