-4

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]
  • Welcome back to SO! As a refesher, please take the [tour] and check out [ask], which has tips like how to write a good title. – wjandrea Jul 07 '22 at 03:14

2 Answers2

1

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)
0

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.

lawliet1035
  • 161
  • 8
  • Beside the point, but `sorted` is a bad variable name since it [shadows](https://en.wikipedia.org/wiki/Variable_shadowing) the builtin `sorted` function. You could use something like `s` instead, or if you want to be verbose, something like `numbers_combined_sorted`. – wjandrea Jul 07 '22 at 03:13
  • I second this ^! I was just writing quick code for a quick understanding but definitely use better naming conventions lol – lawliet1035 Jul 07 '22 at 03:15