Gaurang Solanki
Gaurang Solanki

Reputation: 81

How python List and Numpy array works?

How array works differently from a python list?

a=[0,1,2,3,4,5,6,7,8,9]
b=2
a==b

gives

False

But

a=np.array([0,1,2,3,4,5,6,7,8,9])
b=2
a==b

gives

array([False, False, True, False, False, False, False, False, False, False])

Upvotes: 1

Views: 44

Answers (3)

Panda50
Panda50

Reputation: 939

First, you don't need to add any ; in python at the end of your line.

Then,

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = 2
a == b

will check if a is equal to b, meaning that it's exactly the same (same type and same content for a list here).

You can use:

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = 2
b in a # True if yes, false if not

for example. There is several methods in python (which you can read here )

With numpy array it's a bit diffrent because the == for a np.array and a int/float will check if the number you want is a value of the array and will give you the result for each element of it. As mentionned by Kevin (in comment) it's called broadcasting.

This will perform this calculation :

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = 2
a == b

result_list = [] 
for value in a:
  result_list.append(b == value)

print(result_list)

which can be more interessant in some case. Don't forget that numpy, because it's written in Cython, is faster than what I wrote here (especially for large arrays/lists)

Upvotes: 1

GuyPago
GuyPago

Reputation: 173

This happens because the __eq__ method is defined differently on numpy arrays comparing to default python lists. Numpy was designed for various proposes, mainly for data science usage, which makes this method definition a very useful (and very fast) choice.

In other words, np.array and lists are different animals. Using each depends on what you're trying to achieve, although for some proposes it doesn't vary much, as they share some similarities.

Upvotes: 1

lolloz98
lolloz98

Reputation: 109

Numpy returns the equality element-wise, see here.

Python checks the equality element-wise: if it finds that two elements are different (or the lengths are different) it returns false, otherwise true. See here paragraph 5.8.

Upvotes: 0

Related Questions