1

temp variable which is assigned before sorting is also gets sorted why?

and what is the best way to create a temporary variable for list.

>>> arr = [3, 2, 4, 1]
>>> temp = arr
>>> arr.sort()
>>> arr
[1, 2, 3, 4]
>>> temp
[1, 2, 3, 4]

whereas:

>>> a = 5
>>> b = a
>>> a
5
>>> b
5
>>> a = 1000
>>> a
1000
>>> b
5
zondo
  • 19,901
  • 8
  • 44
  • 83
codenut
  • 683
  • 1
  • 7
  • 21
  • Dont do temp = arr, make a copy instead. –  May 21 '17 at 23:50
  • `temp = arr` means they are both names for the same `list`. – Peter Wood May 21 '17 at 23:53
  • 1
    You can create a [**`sorted`**](https://docs.python.org/2/library/functions.html#sorted) list from another sequence: `arr = sorted(temp)`. See also [How To: sorting](https://wiki.python.org/moin/HowTo/Sorting) – Peter Wood May 21 '17 at 23:58
  • Your first and second pieces of code are not really parallel. If you were to change `arr.sort()` to `arr = sorted(arr)`, you would then be reassigning `arr` to a different object instead of changing the one it was referring to. The basic idea is that objects do not have names; names refer to objects. You can have multiple names referring to the same object. Making a name point to a different object doesn't effect the other name, but changing the object itself is reflected in all names. – zondo May 22 '17 at 01:22

2 Answers2

2

It is worth noting that using .sort() modifies the original list, whereas sorted() will return a new sorted list. This website has a good explanation for the topic.

Jeremy
  • 1,894
  • 2
  • 13
  • 22
1

temp is a name pointing to the same list. To create a copy of the list, you can do

temp = list(arr)

and you should see that if you run

arr = [1, 2, 3, 4]
temp = list(arr)
temp[0] = 2
arr != temp # will return true because it is a new object
Garrett Kadillak
  • 1,026
  • 9
  • 18