2

When a list is sorted, perhaps in ascending numerical order (for integer only list) or alphabetical order in case of strings (for string only list), can I say that the list is mutated, considering the fact that the index number of the items in the list have been changed? For example:

x = ["Alexa", "Siri", "Cortana"]
x_sorted = sorted (x)
print (x_sorted)
# ["Alexa", "Cortana", "Siri"]
print (x)
# ["Alexa", "Siri", "Cortana"]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
Ahnaf
  • 105
  • 2
  • 8
  • You haven't mutated the list though, you've created a copy with items in a different order. If you did `x.sort()`, that would be mutating x. – Daniel Roseman Oct 10 '16 at 13:13

1 Answers1

3

It depends how you do the sort. If your initial list is

>>> x = ["Alexa", "Siri", "Cortana"]

using sorted will create a new list, and will leave the original unmutated

>>> sorted(x)
['Alexa', 'Cortana', 'Siri']
>>> x
['Alexa', 'Siri', 'Cortana']

However the sort method will sort the list in-place, and therefore does mutate the list in doing so

>>> x.sort()
>>> x
['Alexa', 'Cortana', 'Siri']
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218