0

i encountered a weird thing about the .sort() command in python 2.7.

to explain i'll use a simple code -

A = [1,3,2]
B = A
B.sort()

print A

in this code i create a non sorted list A, i then copy that list into B, sort B and print A. for some reason when i print A i get a sorted list [1,2,3] even though i used the sort command on B.

on the other hand if i'll write the following code -

A = [1,3,2]
B = A
B[1] = 123

print A

it'll print A as it should - [1,3,2]

if someone can suggest an explanation it'll be great thanks

Ido GD
  • 45
  • 6
  • You didn't make a copy; you only created an additional reference to the same object. This has little to do with sorting; `list.sort()` sorts the list in-place so all references to the list will see the changes made. – Martijn Pieters Oct 17 '15 at 13:40
  • Your second example prints `[1, 123, 2]`, as it should. It'll never print `[1, 3, 2]`. – Martijn Pieters Oct 17 '15 at 13:41

1 Answers1

0

This has nothing to do with sort().

B = A

Now B and A are two different names for, or references to, the same list object.

You can confirm this by calling id() and seeing that it reutns the same value for both names.

If you want a copy of the list, do:

B = list(A)
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328