1
file_list = os.listdir(os.getcwd)
files = file_list.sort()

If I have a list based on a directory listing as above, why does it sometimes return NoneType if using the files.sort() function but returns intended sort using the sorted(files) function?

1
  • Could you post some of the example directory listings that you are testing? Commented Sep 5, 2015 at 8:31

2 Answers 2

10

list.sort() does an in place sort whereas sorted(list) returns a copy of the sorted list. This means .sort() will return None as it has no return, thus defaulting in None. Using sorted() is usefull if you want to keep the original list, as .sort() destroys the original order.

>>> my_list = [3, 1, 2]
>>> sorted_list = sorted(my_list)
>>> sorted_list
[1, 2, 3]
>>> my_list
[3, 1, 2]
>>> print my_list.sort()
None
>>> my_list
[1, 2, 3]
Sign up to request clarification or add additional context in comments.

6 Comments

i don't quite understand the comment. sort() will always return None
@conma293 if you definitely want to use .sort() just call file_list.sort() without assigning it and after the call just operate on file_list as it will be sorted
But if I called files=file_list.sort() wouldn't that essentially be calling a copy of the sorted in place list and assigning it to files?
but if I assign a new variable files=file_list.sort() , isn't that the same as the sorted() function?
Beautiful that's what I was after! Thanks
|
3

list.sort() is a method of list and sorts the list that it is called on in-place and doesn't return anything.

sorted(collection) takes any iterable (it can be a list, set, tuple, or even a generator) and returns a list with all the items in sorted order.

Since sorted(collection) works any iterable and returns a list it is very useful when chaining method calls or when you can't use list.sort(), such as when iterating over the items in a dictionary (which is a tuple):

dct = { "c": 1, "b": 3, "a": 7 }
for key, value in sorted(dct.items()):
    print("{} = {}".format(key, value))

In your case it doesn't really matter, but I'd go with

file_list = sorted(os.listdir(os.getcwd))

purely out of personal preference (it takes up less space).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.