0

I've been experiencing some strange behavior with numpy arrays. Consider the code below:

import numpy as np

# 1
a = [np.arange(16)]
b = a
print(f'b = {b}')

# 2
b[0] = a[0][::2]
print(f'b = {b}')

# 3
b[0] = a[0][::2]
print(f'b = {b}')
b = [array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])]
b = [array([ 0,  2,  4,  6,  8, 10, 12, 14])]
b = [array([ 0,  4,  8, 12])]

I'd expect b in section 2 to be the same as the b in section 3, but for some reason it seems to be different. This doesn't seem to happen when a is a 1D array—writing b = a[::2] twice gives the same value for b. Why is this happening when a is a 2D array?

8
  • 1
    a is not a 2D array. You made a list with an array inside. Commented Sep 13, 2020 at 4:23
  • It is working as designed. You are asking b[0] to be reassigned to every other value of a. Remember, you defined b = a so both b and a are same lists. Just referenced. Commented Sep 13, 2020 at 4:24
  • 1
    Also, b = a doesn't make a copy. Commented Sep 13, 2020 at 4:24
  • 1
    @JoeFerndz: b and a are the same list. They're not arrays. Commented Sep 13, 2020 at 4:24
  • I see, seems like an elementary mistake. But then why doesn't this happen when a = np.arange(16)? Is there something fundamentally different between a list and an array? Commented Sep 13, 2020 at 4:26

1 Answer 1

1

In your code, you have given b = a So b is just making a reference of a. Every time you change the value of b, you are also making a change to value of a. For more details on assignment vs copy vs deep copy, please refer to this link

b[0] = a[0][::2]

The above code is asking b to have skipped values of b (a is same as b). So every time you do this, it is reducing it further.

If you want to make a copy, use

b = a.copy()

or

b = a[::]
Sign up to request clarification or add additional context in comments.

2 Comments

So why doesn't this happen with a = np.arange(16)? It seems as though b isn't made a reference of a if a is a numpy array?
np.arange() Return evenly spaced values within a given interval. Here, you are just calling a numpy function to create an evenly spaced values. b=a is assignment of two variables. In this case you just make the reference of b and a as same.

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.