sort list so that large strings are not next to large strings

One approach would be to sort list by length first and then form a new list where elements are taken from opposite ends of new list. This way you will have the longest available item followed by the shortes available.

input_list = ["1", "22", "333", "4444"]
sorted_by_len = sorted(input_list, key=len)
output = []
for i in range(len(sorted_by_len) // 2):
if sorted_by_len:   # if len was odd, have to deal with last element
    output += sorted_by_len

Result for given input:

['4444', '1', '333', '22']

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top