Search code examples
arrayspython-3.xsortingprintingreturn

Empty Array returned when using array.sort() with return or print in Python


print(array.sort())
return array.sort()

print or return an empty array = []

while if I do this

array.sort()
print(array)
  OR
array.sort()
return array

Gives me a sorted array = [1, 4, 9, 10]

Why is it like this I tried understanding the working of the inbuilt code for sorting but couldn't understand? Is it a memory problem or something else?


Solution

  • sort sorts the array and returns None. For example:

    >> a1 = [1, 9, 10, 4]    
    >> a1.sort()
    >> print(a1)
    [1, 4, 9, 10]
    

    On the other hand, sorted returns a sorted copy of the original array, but the original array remains unsorted.

    >> a2 = [1, 9, 10, 4]    
    >> print(sorted(a2))
    [1, 9, 10, 4] 
    >> print(a2)
    [1, 4, 9, 10]