ChatGPT解决这个技术问题 Extra ChatGPT

Why does "return list.sort()" return None, not the list?

I've been able to verify that the findUniqueWords does result in a sorted list. However, it does not return the list. Why?

def findUniqueWords(theList):
    newList = []
    words = []

    # Read a line at a time
    for item in theList:

        # Remove any punctuation from the line
        cleaned = cleanUp(item)

        # Split the line into separate words
        words = cleaned.split()

        # Evaluate each word
        for word in words:

            # Count each unique word
            if word not in newList:
                newList.append(word)

    answer = newList.sort()
    return answer
I don't think you need to turn item into a string so many times. Once is normally enough and it's cleaner to do it on the input to cleanUp as well.
Just a silly thought, but if you want a list of unique items, why don't you just convert into a set? You can then convert them back to a list if you need. theSet= set(theList) And you are done, you only need to cast it back to list: theList = list(theSet) Done. Easy.
Adding to what @runlevel0 said (which is a good idea): You can convert a theSet' into a sorted list with sorted(theSet)`.
very irregular language
Just because chaining is a common API idiom in one language doesn't mean it it must be in every language, and it has very little to do with functional programming (which encourages the use of immutable values, which makes the question of mutating method returning a reference to the object moot).

I
Ismail Badawi

list.sort sorts the list in place, i.e. it doesn't return a new list. Just write

newList.sort()
return newList

return sorted(newList) is shorter. Doesn't matter here since the variable is local, but in-place sort could change a shared variable in some cases.
It's interesting that if an entry is added to a list, either a.append('x'), or a.extend('x) you can't chain sort() on the end either. It has to be split into 2 lines. It would have been nicer had the methods returned the list! docs.python.org/3/tutorial/datastructures.html This same message bit me by doing just that. Consequently you have to break the thing into two lines, You have to use .sort() NOT sorted() on the list afterwards, since this generates the same error l = ['1']; l = sorted(l.append('2')) (I just added semi-colon so you could cut/paste and run)
Why was sort function designed this way? is there any performance overhead or other drawbacks if return the sorted list instead of None?
I also faced the folowing problem : print(newList.sort()) gave None. However when i did, newList.sort() and then print(newList) it worked.
@LeiYang: Pop quiz: If I do b = a.sort(), then b.pop(), what is the effect on a? In some languages, .sort returns a copy of a that has been sorted, in others, it sorts in-place and returns a reference to a. Python removes ambiguity by having in-place mutation return None, not an alias to the thing they were called on, so there's less confusion. You use sorted if you need a copy (and it works on all iterables, not just list, consistently returning a list in sorted order). There'd be roughly zero performance overhead to alist.sort() returning alist, just uncertainty.
N
NPE

The problem is here:

answer = newList.sort()

sort does not return the sorted list; rather, it sorts the list in place.

Use:

answer = sorted(newList)

This is what most will need: difference between list.sort() and sorted(list).
Refer this doc for more detail - realpython.com/python-sort
P
Peter Mortensen

Here is an email from Guido van Rossum in Python's dev list explaining why he choose not to return self on operations that affects the object and don't return a new one.

This comes from a coding style (popular in various other languages, I believe especially Lisp revels in it) where a series of side effects on a single object can be chained like this: x.compress().chop(y).sort(z) which would be the same as x.compress() x.chop(y) x.sort(z) I find the chaining form a threat to readability; it requires that the reader must be intimately familiar with each of the methods. The second form makes it clear that each of these calls acts on the same object, and so even if you don't know the class and its methods very well, you can understand that the second and third call are applied to x (and that all calls are made for their side-effects), and not to something else. I'd like to reserve chaining for operations that return new values, like string processing operations: y = x.rstrip("\n").split(":").lower()


Amusingly, split(":").lower() is a bad chain because split returns a list that doesn't have a lower method.
z
zxq9

Python has two kinds of sorts: a sort method (or "member function") and a sort function. The sort method operates on the contents of the object named -- think of it as an action that the object is taking to re-order itself. The sort function is an operation over the data represented by an object and returns a new object with the same contents in a sorted order.

Given a list of integers named l the list itself will be reordered if we call l.sort():

>>> l = [1, 5, 2341, 467, 213, 123]
>>> l.sort()
>>> l
[1, 5, 123, 213, 467, 2341]

This method has no return value. But what if we try to assign the result of l.sort()?

>>> l = [1, 5, 2341, 467, 213, 123]
>>> r = l.sort()
>>> print(r)
None

r now equals actually nothing. This is one of those weird, somewhat annoying details that a programmer is likely to forget about after a period of absence from Python (which is why I am writing this, so I don't forget again).

The function sorted(), on the other hand, will not do anything to the contents of l, but will return a new, sorted list with the same contents as l:

>>> l = [1, 5, 2341, 467, 213, 123]
>>> r = sorted(l)
>>> l
[1, 5, 2341, 467, 213, 123]
>>> r
[1, 5, 123, 213, 467, 2341]

Be aware that the returned value is not a deep copy, so be cautious about side-effecty operations over elements contained within the list as usual:

>>> spam = [8, 2, 4, 7]
>>> eggs = [3, 1, 4, 5]
>>> l = [spam, eggs]
>>> r = sorted(l)
>>> l
[[8, 2, 4, 7], [3, 1, 4, 5]]
>>> r
[[3, 1, 4, 5], [8, 2, 4, 7]]
>>> spam.sort()
>>> eggs.sort()
>>> l
[[2, 4, 7, 8], [1, 3, 4, 5]]
>>> r
[[1, 3, 4, 5], [2, 4, 7, 8]]

difference between lst.sort() vs sorted(lst) is helpful
M
Mike Graham

Python habitually returns None from functions and methods that mutate the data, such as list.sort, list.append, and random.shuffle, with the idea being that it hints to the fact that it was mutating.

If you want to take an iterable and return a new, sorted list of its items, use the sorted builtin function.


P
Peter Mortensen

To understand why it does not return the list:

sort() doesn't return any value while the sort() method just sorts the elements of a given list in a specific order - ascending or descending without returning any value.

So problem is with answer = newList.sort() where answer is none.

Instead you can just do return newList.sort().

The syntax of the sort() method is:

list.sort(key=..., reverse=...)

Alternatively, you can also use Python's in-built function sorted() for the same purpose.

sorted(list, key=..., reverse=...)

Note: The simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list.

So in your case answer = sorted(newList).


> Instead you can just do return newList.sort()...... is misleading. It will return None not the sorted list. So yes you can do it but will probably not do what was intended.
d
doublefelix

A small piece of wisdom which I didn't see in other answers:

All methods for mutable objects in python (like lists) which modify the list return None. So, for lists this also includes list.append(), list.reverse(), etc. That's why the syntax should be

myList.sort()

Meanwhile, methods for any immutable object (like strings) must be assigned like so:

myString = myString.strip()


Exactly my problem. If you're using a lambda, use sorted instead
u
user8153007

you can use sorted() method if you want it to return the sorted list. It's more convenient.

l1 = []
n = int(input())

for i in range(n):
  user = int(input())
  l1.append(user)
sorted(l1,reverse=True)

list.sort() method modifies the list in-place and returns None.

if you still want to use sort you can do this.

l1 = []
n = int(input())

for i in range(n):
  user = int(input())
  l1.append(user)
l1.sort(reverse=True)
print(l1)