user7387342
user7387342

Reputation: 13

Using lists in functions in python

I am not able to understand what is happening in the code below

#swaps list in index 1
L=[[1,2],[3,4]]
def swap(X):
  beta=X[:]
  beta[1][0],beta[1][1]=beta[1][1],beta[1][0]
  return beta
def code(W):
  alpha=W[:]
  print swap(alpha)
  return swap(alpha)
print code(L)

It gives an output

[[1, 2], [4, 3]]
[[1, 2], [3, 4]]

While i am expecting

[[1, 2], [4, 3]]
[[1, 2], [4, 3]]

Upvotes: 1

Views: 58

Answers (1)

Keiwan
Keiwan

Reputation: 8251

The reason for that is that

alpha = W[:]    # and also beta=X[:]

only create a shallow copy of the list. This means that only the outer list is actually copied. This outer list then again contains references to more lists - these lists are in not copied (only the references to them).

So your copies alpha and beta are always referring to the same nested lists and swapping the elements in these lists. This is why you can see the swapping happen twice after calling

swap(alpha)

twice.

If you want to make a deep copy you can use the copy module and write

alpha = copy.deepcopy(W)   # instead of alpha = W[:]

and

beta= copy.deepcopy(X)     # instead of beta = X[:]

Doing this will give you your expected output:

[[1, 2], [4, 3]]
[[1, 2], [4, 3]]

Upvotes: 3

Related Questions