I'm learning Python and would appreciate any (and all) feedback to improve myself.
input/output example:
>>> list_of_words = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']
>>> sort_anagrams(list_of_words)
[['deltas', 'desalt', 'slated', 'salted', 'staled', 'lasted'], ['retainers', 'ternaries'], ['pants'], ['generating', 'greatening'], ['smelters', 'termless', 'resmelts']]
Here is the code I wrote, it worked well for the above list. Looking for feedback on complexity, overall design, readability and any other thing that pops to mind when reviewing, thanks!
# process list of strings, construct nested list of anagrams.
list_of_strings = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']
list_of_lists = []
temp_list = []
def sort_anagrams(list_of_strings):
if len(list_of_strings) > 1:
temp_list = [list_of_strings[0]] # create temp list to be eventually appended to main list
popped_list = list_of_strings # list of anagrams to remove from source list after iteration, without deleting source list
popped_list.pop(0) # remove the first item as it's already in the temp_list
strings_to_pop = []
for string in popped_list:
if sorted(string) == sorted(temp_list[0]):
temp_list.append(string) # passing anagram test so append to temp_list
strings_to_pop.append(string) # create list of items to remove popped_list
list_of_lists.append(temp_list) # append temp_list as a list element
for string in strings_to_pop:
popped_list.remove(string) # remove all strings that were deemed anagram to remove possible duplications
sort_anagrams(popped_list) # running the function again on list remainder
elif len(list_of_strings) == 1:
temp_list.append(list_of_strings[0])
list_of_strings.pop(0)
list_of_lists.append(temp_list) # append temp_list as a list element
sort_anagrams(popped_list)
else:
print('you have reached the end and sorted all anagrams. here is the list of anagram lists: \n \n', list_of_lists)
sort_anagrams(list_of_strings)
```