Comparing object ids of two numpy arrays

前端 未结 2 1180
眼角桃花
眼角桃花 2021-01-19 10:11

I have been using numpy for quite a while but I stumbled upon one thing that I didn\'t understand fully:

a = np.ones(20)
b = np.zeros(10)

print         


        
2条回答
  •  终归单人心
    2021-01-19 10:57

    It's important to note that everything in Python is an object, even numbers and Classes. You have taken 2 numpy array object and each of contains same values i.e 0. When you say:

    print('id of 0 =',id(0))
    
    a = 0
    print('id of a =',id(a))
    
    b = a
    print('id of b =',id(b))
    
    c = 0.0
    print('id of c =',id(c))
    

    The answer you get something like (your case it's different):

    id of 0 = 140472391630016
    id of a = 140472391630016
    id of b = 140472391630016
    id of c = 140472372786520
    

    Hence, integer 0 has a unique id. The id of the integer 0 remains constant during the lifetime. Similar is the case for float 0.0 and other objects. So in your case a[0] or b[0] object id of zero will remain same until or unless it is alive because both contains 0 as object value. Each time you print a[0] or b[0] in different line you return it's different identity of object because you triggering it at different line hence different lifetime. You can try:

    print(id(a)==id(b))
    print(id(a),id(b))
    print(id(a[0])==id(b[0]))
    print(id(a[0]),id(b[0]))
    

    The output will be:

    False
    2566443478752 2566448028528
    True
    2566447961120 2566447961120
    

    Note that second line will return to you 2 different identity of object of numpy array type because both are different list.

提交回复
热议问题