M.K
M.K

Reputation: 1495

Differences between using numpy append or array append - Python

I have this basic example to understand the numpy append method.

distances=[]
for i in range (8):
    distances = np.append(distances, (i))
print(distances)

distances=[]
for i in range (8):
    distances.append(i)
print(distances)

The output gives me 2 arrays but are in different format (or what I understand of different format).

[ 0.  1.  2.  3.  4.  5.  6.  7.]
[0, 1, 2, 3, 4, 5, 6, 7]

What is the exact different of both arrays and why is the output different?

Upvotes: 3

Views: 1532

Answers (3)

StefanS
StefanS

Reputation: 1770

Your second method is pure python and doesn't use any numpy, so the type starts as list ([]) and stays that way, because list.append() leaves list as a list. It contains integers because that's what you get out of range and nothing in your code changes them.

The first method uses numpy's append method that returns an ndarray, which uses floats by default. This also explains why your returned array contains floats.

Upvotes: 4

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95908

The first gives you an numpy.ndarray and is the result of numpy methods, the second produces a list and is a result of list methods. Numpy arrays and Python lists are not the same thing.

Numpy arrays are essentially object-oriented wrappers around fix-sized, typed, true multidimensional arrays. numpy array methods are optimized for vectorized numerical calculations, and along with scipy, provide powerful scientific computing and linear algebra capabilities.

Python list objects are heterogeneous, resizable, array-lists. They are optimized for constant-time .append. Indeed, both of these for-loops will scale very differently. numpy.ndarray.append requires creating an entirely new array each iteration. Python list have amoratized constant time append. Thus, you will see quadratic growth in runtime as the size of your numpy.ndarray scales, whereas with the list, you will see linear scaling.

Upvotes: 1

Arusekk
Arusekk

Reputation: 881

The first code

distances=[]
for i in range (8):
    distances = np.append(distances, (i))
print(distances)

results in distances being an array of floats. While the second code

distances=[]
for i in range (8):
    distances.append(i)
print(distances)

results in distances being a list of ints.

arrary is a numpy type (main difference: faster, all items have the same type), while list is python-internal (main difference: works without numpy, can hold any mixed types).

Upvotes: 1

Related Questions