python - sort() and reverse() functions do not work -
i trying test how lists in python works according tutorial reading. when tried use list.sort() or list.reverse(), interpreter gives me none.
please let me know how can result these 2 methods:
a = [66.25, 333, 333, 1, 1234.5] print(a.sort()) print(a.reverse())
.sort() , .reverse() change list in place , return none see mutable sequence documentation:
the
sort(),reverse()methods modify list in place economy of space when sorting or reversing large list. remind operate side effect, don’t return sorted or reversed list.
do instead:
a.sort() print(a) a.reverse() print(a) or use sorted() , reversed() functions.
print(sorted(a)) # sorted print(list(reversed(a))) # reversed print(a[::-1]) # reversing using negative slice step print(sorted(a, reverse=true)) # sorted *and* reversed these methods return new list , leave original input list untouched.
demo, in-place sorting , reversing:
>>> = [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 , reversed lists:
>>> = [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] >>> # input list untouched [66.25, 333, 333, 1, 1234.5]
Comments
Post a Comment