0

I'm trying to understand why :

 w=[0.1,0.2,0.3,0.5,0]
 print(w[w!=0])

outputs : 0.2,

while

 w=[0.1,0.2,0.3,0.5,0]
 w=np.asarray(w)
 print(w[w!=0])

outputs : [0.1 0.2 0.3 0.5], which seems more logical

So : why lists do return the second element ?

2
  • 1
    Ultimately, they react differently because they are different types. Much like a cat and a tiger react differently to a poke with a stick Commented Oct 9, 2019 at 9:35
  • It wasn't a surprise to know that there are two different data type. I was looking for a comprehension of WHY does list reacts by throwing the second element ? Commented Oct 9, 2019 at 9:45

1 Answer 1

1

A list and an ndarray implement comparison differently. In particular:

  • a list returns a single bool value of True or False when compared to something else. Clearly a list w is not the value 0.2 so w != 0.2 returns True

  • an ndarray implements comparison by returning an ndarray of booleans, representing each array element’s comparison. Thus, w != 0.2 returns [True False True True]

Thus

  • for a list, w[w!=0.2] is w[True] and this is treated as meaning w[1]

  • for an ndarray it is w[ ndarray([True False True True]) ] which then leverages numpy’s array indexing to return only those elements where the Boolean is True

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

1 Comment

This is clarifying why i can poke a cat with a stick and not a tiger ! Thanks

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.