Home > Enterprise >  Why is a different outcome occurring on the following use of sort
Why is a different outcome occurring on the following use of sort

Time:09-16

I was doing a puzzle and where i had to add 2 lists having same length to a new list and sort the list by the second element of the list.

for x in range(n):
            tmp.append([start[x],end[x]])

where start and end are lists containing equal elements and n is the length of start and end.

Now, idk why a difference / error occurs between the use of following code.

end.sort()
for x in range(n):
    tmp.append([start[x],end[x]])

and

for x in range(n):
    tmp.append([start[x],end[x]])
tmp.sort(key=lambda x:x[1])

EDIT:-
Input list

start=[1, 3, 0, 5, 8, 5]
end=[2, 4, 6, 7, 9, 9]

output by sorting first

[[1, 2], [3, 4], [0, 6], [5, 7], [8, 9], [5, 9]]

output by sorting later

[[1, 2], [3, 4], [0, 6], [5, 7], [8, 9], [5, 9]]

works fine for this list but doesn't work for a bigger array (array contains 80 elements thats why not uploading here)

CodePudding user response:

If you sort end first, you combine the original order of start with the sorted order of end.

If you combine the two lists first and then sort by the end element, the start elements will get reordered, too, as they "tag along" with their end partner. Consider

start = [1, 2, 3]
end   = [3, 2, 1]

Now, sorting end and combining, you'll end up with:

start = [1, 2, 3]
end   = [1, 2, 3]
# =>
tmp = [[1, 1], [2, 2], [3, 3]]

Combining first, however, produces:

tmp = [[1, 3], [2, 2], [3, 1]]

And sorting this by the second element, will shuffle the old start elements as well:

tmp.sort(key=lambda x:x[1])
# [[3, 1], [2, 2], [1, 3]]

Side note: Check out zip:

tmp = list(zip(start, end))
  • Related