Python # sort

sort

sort and sorted

Sort and sorted are mainly used when sorting list data. If you want to get only the sorted result without changing the original contents, you can use sorted. Also, sorted can be used for tuples and iterators. The difference in behavior is as follows.

a = [4, 6, 2, 8]
b = [5, 3, 9, 7, 1]

a.sort()
print(a)
print(sorted(b))
print(b)

Execution result

[2, 4, 6, 8] [1, 3, 5, 7, 9] [5, 3, 9, 7, 1]

reserved reserved is a function used when sorting in reverse order. Like the sorted method, it is a function that returns only the sorted result without changing the content itself.

a = [4, 6, 2, 8]
print(reserved(a))

Execution result

[8, 6, 4, 2]

(Reverse sort using slice specifier)
a = [4, 6, 2, 8]
print(sorted(a)[::-1])

Execution result

[8, 6, 4, 2]

Recommended Posts

[Python] Sort
Python # sort
Python
Bubble sort in Python
Python self-made class sort
[Memo] Python3 list sort
Python sort cheat sheet
Custom sort in Python3
[Python] Sort collection types
sort
Sort Python module imports alphabetically
Naturally sort Path in Python
Python basic dict sort order
Sort huge files with python
python in mongodb in descending sort
Python beginners organize bubble sort
Sort by date in python
About Python sort () and reverse ()
kafka python
Insertion sort
Selection Sort
[Python] Random processing (create, select, sort)
Python basics ⑤
python + lottery 6
Built-in python
Python comprehension
Python technique
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
[Python] Sort iterable by multiple conditions
python function ①
Python basics
Python memo
ufo-> python (3)
Python comprehension
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Python Jinja2
Python increment
python tips
Installing Python 3.4.3.
Try python
Python memo
Python iterative
Python algorithm
[Python] Variables
Python functions
Python sys.intern ()
Python decimals
python underscore
Python summary
Start python
Note: Python
Python basics ③
Python basics