1

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

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

You should mention that this is called broadcasting.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.