I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?
Share
People seem to be over complicating this.. Just combine the two lists, then sort them:
..or shorter (and without modifying
l1):..easy! Plus, it’s using only two built-in functions, so assuming the lists are of a reasonable size, it should be quicker than implementing the sorting/merging in a loop. More importantly, the above is much less code, and very readable.
If your lists are large (over a few hundred thousand, I would guess), it may be quicker to use an alternative/custom sorting method, but there are likely other optimisations to be made first (e.g not storing millions of
datetimeobjects)Using the
timeit.Timer().repeat()(which repeats the functions 1000000 times), I loosely benchmarked it against ghoseb’s solution, andsorted(l1+l2)is substantially quicker:merge_sorted_liststook..sorted(l1+l2)took..