0

For example:

a = [5,3,7,5]

b = a

b.sort()

print a
print b

a = [3,5,5,7]

b = [3,5,5,7]

I don't want the programm to change a. How can I avoid this?

PS: Yes i know the question has been asked before, but these questions were asked for C or C#, not Python.

Ashish Acharya
  • 3,349
  • 1
  • 16
  • 25
Quotenbanane
  • 263
  • 1
  • 6
  • 16
  • 1
    Use `sorted(arr)` instead – Nick is tired Aug 13 '18 at 09:38
  • 2
    Use `b=a.copy()`. By using `b=a`, you are creating a reference to initial variable `a`. All the changes in `b` will therefore be reflected in `a` – Sheldore Aug 13 '18 at 09:39
  • 1
    @Aran Maybe add https://stackoverflow.com/questions/36139/how-to-sort-a-list-of-strings, it may say strings but same applies to numbers and accepted answers mentions how to not change original array – Nick is tired Aug 13 '18 at 09:40
  • 1
    @NickA I don't think that tells the OP anything they didn't know. They clearly already know how to sort a list, no? As far as I can tell, the question is why `b = a` doesn't make a copy. – Aran-Fey Aug 13 '18 at 09:43
  • 1
    @Aran-Fey I think it does in that they can use `b = sorted(a)`, instead of `b = a.copy()` followed by sorting, however it is only a suggestion so feel free not to – Nick is tired Aug 13 '18 at 09:44
  • Thanks guys! I didn't know b = a is just creating a reference and not an independent variable. I'm using import copy + copy.copy(a) now and it works fine. – Quotenbanane Aug 13 '18 at 09:45
  • @NickA I like your answer even better because as you said, b = a.copy() becomes no longer necessary – Quotenbanane Aug 13 '18 at 09:50

0 Answers0