What are the different between this two code. they provide same output. explain please

Question:

Code written by me :

def combine_sort(lst1, lst2):
    comdined = sorted(lst1 + lst2)
    print(comdined)

combine_sort([4, 10, 2, 5], [-10, 2, 5, 10])

code given in example:

def combine_sort(lst1, lst2):
  unsorted = lst1 + lst2
  sortedList = sorted(unsorted)
  return sortedList
print(combine_sort([4, 10, 2, 5], [-10, 2, 5, 10]))

both program produce same output

[-10, 2, 2, 4, 5, 5, 10, 10]
Asked By: Rabin Thami

||

Answers:

The one on the top outputs to a console using print which will put the variable in the console for you to see but you can’t set a variable equal to the result the same way you can with the one on the bottom. Returning a value (as you do on the bottom function) allows you to store that value in memory while printing only outputs it, generally used for debugging.

This is the difference:

def combine_sort(lst1, lst2):
  unsorted = lst1 + lst2
  sortedList = sorted(unsorted)
  return sortedList


#you can store your function in a variable like this
sorted = combine_sort([4, 10, 2, 5], [-10, 2, 5, 10])
print(sorted)

In the above example I stored your function in a variable called sorted and printing that variable will provide the same output. It’s best practice to use return rather than print on a function depending on what the purpose is.

Answered By: SWELLZ

The main difference is that in the example the sortedList is returned from the function and in your code it is not.

If you wanted to save the output, you could only do so with the second one.
In the first one the combined variable is lost once the function exits.
In the second one, when the function exits it is returning sortedList.

You could assign this return value to a variable by calling:

output = combine_sort([4, 10, 2, 5], [-10, 2, 5, 10])
print(output)
Answered By: Tope Lourenco
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.