List.sort() not working

Here is a code snippet from my program that illustrates the issue I am running into.

self.models_list = list(self.models.keys())
print('dir: ',dir(self.models_list))
print('type: ', type(self.models_list))
print('models_list: ',self.models_list)
print('sorted: 'self.models_list.sort())

Output:

dir: [‘add’, ‘class’, ‘class_getitem’, ‘contains’, ‘delattr’, ‘delitem’, ‘dir’, ‘doc’, ‘eq’, ‘format’, ‘ge’, ‘getattribute’, ‘getitem’, ‘gt’, ‘hash’, ‘iadd’, ‘imul’, ‘init’, ‘init_subclass’, ‘iter’, ‘le’, ‘len’, ‘lt’, ‘mul’, ‘ne’, ‘new’, ‘repr’, ‘reversed’, ‘rmul’, ‘setattr’, ‘setitem’, ‘str’, ‘append’, ‘clear’, ‘copy’, ‘count’, ‘extend’, ‘index’, ‘insert’, ‘pop’, ‘remove’, ‘reverse’, ‘sort’]

type: <class ‘list’>

models_list: [‘TheBloke_Wizard-Vicuna-30B-Uncensored-GPTQ’, ‘NousResearch_Meta-Llama-3-8B.gguf’, ‘llama-2-7b-chat.Q4_0.gguf’, ‘llama-2-7b-chat.Q3_K_L.gguf’, ‘TheBloke_Upstage-Llama-2-70B-instruct-v2-GPTQ’, ‘llama-2-7b-chat.Q4_K_M.gguf’, ‘Meta-Llama-3-70B-Instruct-Q3_K_S.gguf’, ‘llama-2-7b-chat.Q6_K.gguf’, ‘llama-2-7b-chat.Q8_0.gguf’, ‘llama-2-7b-chat.Q5_K_M.gguf’, ‘Meta-Llama-3-70B-Instruct-Q5_K_M.gguf’, ‘unsloth_llama-3-8b-bnb-4bit’, ‘llama-2-7b-chat.Q5_K_S.gguf’, ‘’, ‘llama-2-7b-chat.Q3_K_S.gguf’, ‘llama-2-7b-chat.Q5_0.gguf’, ‘Meta-Llama-3-70B-Instruct-Q4_K_S.gguf’, ‘Meta-Llama-3-70B-Instruct-Q4_K_M.gguf’, ‘llama-2-7b-chat.Q2_K.gguf’, ‘llama-2-7b-chat.Q3_K_M.gguf’, ‘llama-2-7b-chat.Q4_K_S.gguf’]

sorted: None

I have created a list, validated that it is a list, I can see the sort method in the list dir(), but when I invoke the sort method, I get None???

What is happening?

Lists in Python are mutable, which means that when you call something like sort on it, it changes the actual list. It doesn’t return a new list. What you want is something like this:

self.models_list.sort()
print('sorted: 'self.models_list)

That’s assuming you don’t need the original order maintained. If you need the original order maintained you’d want to make a copy of the list before sorting it.

1 Like

my_list.sort() sorts my_list and returns None.

sorted(my_list) returns a sorted copy of my_list.

4 Likes

Got it thank you both for the reply.