## DEV Community is a community of 901,019 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

HHMathewChan

Posted on • Originally published at rebirthwithcode.tech

# Python Exercise 19:advanced list sort

## Question

• Create a function that
• takes a list of numbers or strings
• and returns a list with the items from the original list stored into sublists.
• Items of the same value should be in the same sublist.
• The sublists should be returned in the order of each element's first appearance in the given list.

### Example

``````advanced_sort([1,2,1,2]) -> [[1,1],[2,2]]
advanced_sort([1234, 1235, 1234, 1235, 1236, 1235])-> [[1234, 1234],[1235, 1235, 1235],[1236]]
advanced_sort(['1234', '1235', '1234', '1235', '1236', '1235'])-> [['1234', '1234'],['1235', '1235', '1235'],['1236']]
``````

## My solution

• algorithm
``````>>separate the original list to different sublist
initialist a empty list: new_list
add the first number of orginal list into new_list
for each number in the original list:
if number equals to the first element of any sublist:
else:
add number to an new empty sublist

``````
• code
``````def advanced_sort(original_list: list) -> list:
# create a list with the first element of the original_list
new_list = [[original_list[0]]]
for index, item in enumerate(original_list):
if index == 0:
continue
# To iterate over every sublist in the new_list
for sublist_index, sublist in enumerate(new_list):
# try:
# if item is the same with first element of the sublist of new list and not already added
if item == sublist[0] and not_added:
# add item to that sublist
sublist.append(item)
# if no same item appear after checking the whole new list and not already added
if item != sublist[0] and sublist_index == len(new_list) - 1 and not_added:
# add the item the end of the new_list
new_list.append([item])
return new_list
``````

## Other solution

``````def advanced_sort(lst):
return [[i] * lst.count(i) for i in sorted(set(lst), key=lst.index)]
``````
• the algorithm
``````>>transform the original list into a set, thus only unique item will appear
>>rearrange the transformed set by the index order
>>count how many time each unique appear in the original list
>>form a new list by putting in each item times their occurance in a sublist
``````

## My reflection

• about `while` loop
• the loop will not instantly end when the boolean condition is changed to false
• need to use if condition to control the execution of code
• Just admire people can write short code in elegant way