0

Why output like this?

    years = [1998,2000,1998,1987]
    
    x = years
    x.sort()
    
    print(x)
    print(years) #why not [1998,2000,1998,1987]

Output:

[1987, 1998, 1998, 2000]
[1987, 1998, 1998, 2000]
Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22
  • 1
    Does this answer your question? https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent – Stef Sep 08 '20 at 08:23
  • The line `x = years` sets `x` to point on `years` list, therefore from that point on they point the same object (until you change it). So, when you sort, you sort the same object and when you print those variables the result is the same sorted array. – Aviv Yaniv Sep 08 '20 at 08:24
  • you can print(id(x)),print(id(years)),to see there address – Zhubei Federer Sep 08 '20 at 08:25
  • 1
    You could also use x = sorted(years) as this created a new sorted list leaving the original – GhandiFloss Sep 08 '20 at 08:27
  • Mandatory link to [Ned Batchelder](https://nedbatchelder.com/text/names.html) – quamrana Sep 08 '20 at 08:28

2 Answers2

1

When you assign it to another variable the reference to that list is assign to another variable, so both of them assigning to same list, then when you change the list, both of them will be change. you can use copy to prevent this to happen, like this:

from copy import copy

x = copy(years)

or

x = years[:]
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0

you copy the location use:

x=years[:]

that will work.