0

I've just learnt copy,shallow copy,and deep copy in python,and I created a list b,then make c equal b.I know it's reasonable to find that the same element share the identical 'id'.Then I think I'll get the similar result in numpy when I make the nearly same steps,however,it shows that the same element has different 'id', I can't figure out how that happens in numpy.

enter image description here

Sudheesh Singanamalla
  • 2,283
  • 3
  • 19
  • 36
Adrian Qin
  • 11
  • 1
  • 1
    Please post code as text, not as screenshots. – Håken Lid Nov 19 '17 at 13:07
  • 1
    Numpy data types are implemented in a completely different way than the builtin python data types. I don't know much about the implementation details, so I can't submit a proper answer. But in general, using `id()` with some datatypes can give unexpected results. – Håken Lid Nov 19 '17 at 13:17
  • Here's another example of implementation specific behavior of `id()` with small integers in cpython. It doesn't really answer this question, but there's some good advice there about using `id()` and the `is` operator. https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers – Håken Lid Nov 19 '17 at 13:22
  • Unless the array `dtype` is `object`, the `id` of an element is meaningless. A array stores values, not pointers. Look at the `type` of the items you `id`. And beware of integers <256. They have special handling in python. – hpaulj Nov 19 '17 at 13:40

1 Answers1

0

You don't need a duplicate reference to produce the result.

import numpy as np
a = np.array([[10, 10], [2, 3], [4, 5]])
for x, y in zip(a, a):
    print(id(x), ',', id(y))

# 52949424 , 52949464
# 52949624 , 52951424
# 52949464 , 52949424

My guess is that when zip iterates over arrays, it triggers indexing in numpy which then returns copied row. Remember that [] in numpy is not like that for list. https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html

You may try this to see why messing with id is not a good idea for numpy.

a[0] is a[0]        # False
a[0] is a[[0]]      # False
Blownhither Ma
  • 1,461
  • 8
  • 18
  • Even with basic indexing, the `id` of a `view` will be different from the `id` of the source. The view is a new array object, even if it shares the data buffer. As a general rule `id` and `is` equivalence are useless when working with `numpy` arrays. – hpaulj Nov 19 '17 at 18:45