0

I am learning python. I am supposed to create a function with two parameters. The first of which must be a list and the second an integer. If its not an integer, it must assert an error. the list must add the integer and then sort it out in ascending order. The list passed through the first parameter must be modified but cannot be returned. I am stuck. I dont know how to achieve this without return. Dont give me the answer, just point me in the right direction.

def my_insert(lista, num):
    assert (type(num) is int)
    lista.append(num)
    lista = sorted(lista)
     
l = [1, 3, 5]
my_insert(l, 4)
print(l)

the print should print [1, 3, 4, 5] and not [1, 3, 5, 4]

4
  • Looks like you want to sort the list inplace... so change: lista = sorted(lista) to be lista.sort() ? Oct 26, 2020 at 14:30
  • Thank you. Works. I did not know you could write that
    – Harsh Dua
    Oct 26, 2020 at 14:38
  • I know this isn't what you asked but it's bad practice to use "assert" for program flow, since there are optional optimizations that disable assert statements. Also, you usually want isinstance(x, y) rather than type(x) is y for polymorphism and duck-typing reasons. You should be able to find more details elsewhere. Good luck.
    – Nzbuu
    Oct 26, 2020 at 15:14
  • @nzbuu My programming course's autocorrector needed assert so i used it. Thank you for the other tip tho
    – Harsh Dua
    Nov 4, 2020 at 0:02

2 Answers 2

1

Just use "lista.sort()" instead of "sorted(lista)".

def my_insert(lista, num):
        assert (type(num) is int)
        lista.append(num)
        lista.sort()
0
def my_insert(lista, num):
    assert type(num) is int
    lista.append(num)
    lista.sort()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.