Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between using numpy append or array append - Python

Tags:

python

numpy

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?

like image 560
M.K Avatar asked Jul 29 '26 00:07

M.K


1 Answers

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.

like image 101
StefanS Avatar answered Jul 30 '26 15:07

StefanS



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!