Vishal1809
Vishal1809

Reputation: 25

Sorting a list through a function in python

def sortt(n):
     return n.sort()

print([1,5,2,3])

it returns none.

Even if I try:

def sortt(n):
    lst = [ ]
    lst = n.sort()
    return lst

print([1,5,2,3]) 

then also returns none.

Upvotes: 1

Views: 42

Answers (1)

Yida Lin
Yida Lin

Reputation: 187

lst.sort() alters lst in-place and returns None.

sorted(lst) returns the sorted list to you while keeping lst unchanged.

Using your provided code as a template:

def sort1(arr):
    arr.sort()
    return arr

print(sort1([1,5,2,3]))

Output: [1, 2, 3, 5]

def sort2(arr):
    return sorted(arr)

print(sort2([1,5,2,3])) 

Output: [1, 2, 3, 5]

Upvotes: 1

Related Questions