Search code examples
numpytypesdifference

Why asarray and list react diffently?


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 ?


Solution

  • 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