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.
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.
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.
If you're not sure how it behaves, read the docs.
Recommended Posts