About Python sort () and reverse ()

Python's List has functions that change the order, such as sort () and reverse (), but if you want to use them, you need to understand the specifications and use them.

I was addicted to the trouble the other day, so I will leave it.

Return value is None

For example, like any other function,

print([1,3,8,7,4].sort())

Even if I write, ** None is displayed **.

In the same way

print([1,3,8,7,4].reverse())

But the result is the same.

Read the Python documentation

sort()

When I read the Python documentation for the time being, I found something like this.

This method changes the sequence in-place to save space when sorting large sequences. It does not return a sorted sequence to make the user aware that this operation is done as a side effect. http://docs.python.jp/3/library/stdtypes.html#list.sort

This means that sort () ** only makes destructive changes, not returns a sorted list **.

Continue to the document

Use sorted () to explicitly request a new list instance

There is.

In other words

l = [1,3,8,7,4]
l.sort()
print(l)

Or write

print(sorted([1,3,8,7,4]))

Must be written

reverse() reverse () also, when I read the document,

The reverse () method changes the sequence in-place to save space when reversing large sequences. To make the user aware that this operation is done as a side effect, it does not return an inverted sequence http://docs.python.jp/3/library/stdtypes.html#mutable-sequence-types

There is. In other words, like sort (), you need to put it in a variable once, make a destructive change, and then print it.

Then, one question comes up.

Is there a reversed () that returns a reversed list? When.

In conclusion, the reversed () function itself exists.

However, unlike sorted (), which returns a sorted list, reversed () returns a ** iterator ** in the reverse order of the given list.

Therefore, it is necessary to generate the list from the iterator.

print([i for i in reversed([1,3,8,7,4])])

And you need to.

But if you just flip the list, it's easier to write.

print([1,3,8,7,4][::-1])

[:: -1] of [1,3,8,7,4] [:: -1] is called a slice, and I will omit the details, but it is a function that can extract a part from the list and create a new list. is.

You can specify three values separated by colons (which can be omitted), the first is the point where the extraction starts, the second is the point where the extraction ends, and the third is the extraction interval.

This time, the interval is -1, so it is incremented by 1 to extract (= extract all), and since it has a minus, extraction starts from the back of the list.

So you'll get a list in reverse order.

As a method of reversing the list,

I want to save memory → reverse ()

I want to add some processing to each value while making an inverted list (double it, etc.) → reversed ()

I want to flip it for the time being → Slice

I think you should use it properly.

Summary

If you're not sure how it behaves, read the docs.

Recommended Posts

About Python sort () and reverse ()
About python objects and classes
About Python variables and objects
About Python, len () and randint ()
About Python datetime and timezone
About Python and regular expressions
Python # About reference and copy
[Python] Sort
Python # sort
About installing Pwntools and Python2 series
About python dict and sorted functions
About dtypes in Python and Cython
About Python pickle (cPickle) and marshal
[Python] About Executor and Future classes
About Python, from and import, as
Reverse Hiragana and Katakana in Python2.7
About python slices
About python comprehension
About Python tqdm.
About python yield
About python, class
About python inheritance
About python, range ()
About python decorators
A story about Python pop and append
About python reference
About Python decorators
[Python] About multi-process
Talking about old and new Python classes
Talking about Python class attributes and metaclasses
Think about depth-priority and width-priority searches in Python
About the difference between "==" and "is" in python
A memo about writing merge sort in Python
A story about modifying Python and adding functions
[Python] Learn about asynchronous programming and event loops
About the * (asterisk) argument of python (and itertools.starmap)
About shallow and deep copies of Python / Ruby
Python> Sort by number and sort by alphabet> Use sorted ()
About Python for loops
Summary about Python scraping
About function arguments (python)
Python and numpy tips
[Python] pip and wheel
Batch design and python
Python iterators and generators
Bubble sort in Python
Python self-made class sort
Python packages and modules
Vue-Cli and Python integration
[Python] Memo about functions
Ruby, Python and map
Summary about Python3 + OpenCV3
About Python3 character code
[Memo] Python3 list sort
Python and Ruby split
About Python development environment
Python: About function arguments
Python, about exception handling
Python sort cheat sheet
Custom sort in Python3
About Python Pyramid traversal