0

I have an array array1 = [[0, 1, 2, 3], [4, 5, 6, 7]] and I want to switch array1[0] and array1[1], which would ideally look like this: array1 = [[4, 5, 6, 7], [0, 1, 2, 3]]. So far I have tried this:

array1 = [[0, 1, 2, 3], [4, 5, 6, 7]]
array2 = array1
array1[0] = array2[1]
array1[1] = array2[0]

But that returns [[4, 5, 6, 7], [4, 5, 6, 7]]. Does anyone know why this is happening?

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
Merp
  • 118
  • 1
  • 10

3 Answers3

1

When you say:

array2 = array1

You are making it so array2 references the same object in memory that array1 does. This is called a "binding" assignment. After that the expression:

array1[0] = array2[1]

is no different than saying:

array1[0] = array1[1]

There no longer is any difference between array1 and array2.

Andrew Allaire
  • 1,162
  • 1
  • 11
  • 19
1

You can try:

array1 = [array1[1], array1[0]]

Then you don't need array2.

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
0

You wanted to copy an array, but:

array2 = array1

is not copying. You just created a new label array2 and pointed it to array1.

To copy an array, you can have a loop at copy.copy() and copy.deepcopy() here: https://docs.python.org/3/library/copy.html

pavelsaman
  • 7,399
  • 1
  • 14
  • 32