0

I was trying to sort list elements inside a function without return when I try to print the list by its name it does not get sorted, but it is sorted inside a function.

I have to update the list inside the function without returning

def sort(n):
    n.append(10)
    sorted(n)
n = [5,1,2,3]
print(n)

Expected : [1,2,3,5] actual: [5,1,2,3]

jpp
  • 159,742
  • 34
  • 281
  • 339
kamalnath L P
  • 37
  • 1
  • 6

1 Answers1

1

I'm sorry, I made a series of mistakes myself. It's a lesson for me too.

def isort(n):
    n.append(10)
    n.sort()  #I used n[:] = sorted(n), but it's superfluous.

n = [5,1,2,3]
isort(n)
print(n)

m = [7,9,3,13]
isort(m)
print(m)

output:

[1, 2, 3, 5, 10]
[3, 7, 9, 10, 13]
  • sort is an existed fuction in python, need to change it to other name. I changed to isort.
  • We have to call the function isort to let it do its work.
  • We need to update the elements in the list to make the list update. [:] Slice notation here.
  • It's better to use different name between function argument and the call. (n and m here).

Many thanks to DYZ, Primusa, and Tomothy32 :)

Til
  • 5,150
  • 13
  • 26
  • 34
  • 2
    Hi, the question states "I have to update the list inside the function without returning" – Primusa Jan 22 '19 at 04:01
  • 2
    `sorted(n)` doesn't change `n`. – iz_ Jan 22 '19 at 04:21
  • 1
    Why not just `n.sort()` instead of `n[:] = sorted(n)`? – iz_ Jan 22 '19 at 04:53
  • @Tomothy32 Yeah... that's right. just call it inside. Thanks again :) – Til Jan 22 '19 at 04:55
  • Also, I don't believe `sort` is a built-in - it's a member of `list`. – iz_ Jan 22 '19 at 04:57
  • @Tomothy32 Then at first why `sort(n)` worked? Sorry I am justing wondering. I'm trying to find the answer in its [source code](https://github.com/python/cpython/blob/master/Objects/listobject.c) now. Thanks anyway :) – Til Jan 22 '19 at 05:01
  • 1
    I don't know, but I can't find `sort`: https://docs.python.org/3/library/functions.html. I'm sure it's not a built-in, but instead a member of `list`. – iz_ Jan 22 '19 at 05:22
  • @Tomothy32 Thanks for the link. Yeah, it's clear it isn't. – Til Jan 22 '19 at 05:29