Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

python - sort() and reverse() functions do not work

I was trying to test how the lists in python works according to a tutorial I was reading. When I tried to use list.sort() or list.reverse(), the interpreter gives me None.

Please let me know how I can get a result from these two methods:

a = [66.25, 333, 333, 1, 1234.5]
print(a.sort())
print(a.reverse())
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.sort() and .reverse() change the list in place and return None See the mutable sequence documentation:

The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.

Do this instead:

a.sort()
print(a)
a.reverse()
print(a)

or use the sorted() and reversed() functions.

print(sorted(a))               # just sorted
print(list(reversed(a)))       # just reversed
print(a[::-1])                 # reversing by using a negative slice step
print(sorted(a, reverse=True)) # sorted *and* reversed

These methods return a new list and leave the original input list untouched.

Demo, in-place sorting and reversing:

>>> a = [66.25, 333, 333, 1, 1234.5]
>>> a.sort()
>>> print(a)
[1, 66.25, 333, 333, 1234.5]
>>> a.reverse()
>>> print(a)
[1234.5, 333, 333, 66.25, 1]

And creating new sorted and reversed lists:

>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print(sorted(a))
[1, 66.25, 333, 333, 1234.5]
>>> print(list(reversed(a)))
[1234.5, 1, 333, 333, 66.25]
>>> print(a[::-1])
[1234.5, 1, 333, 333, 66.25]
>>> print(sorted(a, reverse=True))
[1234.5, 333, 333, 66.25, 1]
>>> a  # input list is untouched
[66.25, 333, 333, 1, 1234.5]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...