0

I have the following code:

def somefunction(word):

  somelist = word
  
  first_random_index = 2
  second_random_index = 9
  
  somelist[first_random_index], somelist[second_random_index] = somelist[second_random_index], somelist[first_random_index]

  return somelist
  
x = [1,2,3,4,5,6,7,8,9,10]
y = somefunction(x)

print (x)
print (y)

My expected output would be:

[1,2,3,4,5,6,7,8,9,10]
[1, 2, 10, 4, 5, 6, 7, 8, 9, 3]

But instead, I am getting:

[1, 2, 10, 4, 5, 6, 7, 8, 9, 3]
[1, 2, 10, 4, 5, 6, 7, 8, 9, 3]

How is that possible? Why is the original x value not printed?

Madno
  • 910
  • 2
  • 12
  • 27
  • 1
    Do `somelist = list(word)` – azro Jan 10 '21 at 08:35
  • 1
    This is because this is pass by reference and pass by value and hence the older value of `x` also gets updated to the new value. Basically `x` and `y` both point to the same memory location and hence if you change one the other also changes – Viraj Doshi Jan 10 '21 at 08:39

0 Answers0