# Do I have to combine the lists before or after sorting?

### Question

In the context of this code challenge, do I have to combine the lists before or after sorting?

You are free to combine the lists either before or after you perform a sort. However, depending on which order you perform the sort and combine steps, it will affect how your code must be implemented.

Say that you choose to sort each list first, before combining them. If you sort them first, then adding the lists together as is can result in an unsorted list. For example,

``````list = [1, 3, 5] + [2, 4, 6]
# [1, 3, 5, 2, 4, 6]
``````

In order to have the combined list sorted as well, you can implement a way to merge the two lists, so that each element is added to the combined list in the correct order.

To do this, you can have pointers in the front of each sorted list, and constantly compare the current element that both pointers are at. Whichever element is less can be added to the combined list, and then the pointer of the lesser element can move to the right by one index to the next element.

This way of merging two sorted lists is part of the `merge sort` algorithm, which you are free to check out and see how it works.

7 Likes

Why did the .sort function not work?

1 Like

Could you be more specific? Under what conditions did it not work? What was the function?

6 posts were merged into an existing topic: Should I use `.sort()` or `sorted()`?

I think this should work)

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

#Uncomment the line below when your function is done
print(combine_sort([4, 10, 2, 5], [-10, 2, 5, 10]))

It’s possible to do it in one line.

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

It gives you a combined sorted list.

1 Like

The shortest solution is:

def combine_sort(lst1, lst2):
return sorted(lst1 + lst2)

8 Likes

Mine seems a bit complex but it worked anyway

``````def combine_sort(lst1, lst2):
new_list = lst1[0:] + lst2[0:]
new_list.sort()
final_list = sorted(new_list)
return final_list

#Uncomment the line below when your function is done
print(combine_sort([4, 10, 2, 5], [-10, 2, 5, 10]))
``````
``````def combine_sort(lst1, lst2):
new_list = (lst1 + lst2)
new_list.sort()
return new_list

#Uncomment the line below when your function is done
print(combine_sort([4, 10, 2, 5], [-10, 2, 5, 10]))
``````