[PYTHON] Difference between sort and sorted (memorial)

Difference between sorted and sorted

Nice to meet you. I am 19 years old aiming to become an engineer. This time, I suddenly wondered when I was solving the exercises, so as a memorandum

Difference between sorted and sorted I will write about. I hope it helps someone's solution. I'm a beginner so it's hard to see, but please forgive me.

I would like to write in the following order. -What is the sort method and how to use it? -What is the sorted function and how to use it? -What's the difference?

What is the sort method and how to use it

According to TechAcademy magazine, the sort method was written as follows. "The sort function is a function for sorting the list. You can sort the list of numbers and strings in ascending or descending order. 』
Also, about how to use "The sort function can be used in the form of" list name.sort () ". You can also optionally set the argument reverse. By default, reverse is False, so if you use reverse without setting it, it will be in ascending order. You can do it in descending order by setting reverse = True. 』
Actually, it seems to be a sort method, but aside from the details. According to the above, the sort method is a method that manipulates the ordering of elements in a "list", for example.

>>>str_list = list("qiita") >>>str_list.sort() >>>print(str_list) ['a', 'i', 'i', 'q', 't']

Or

>>>str_list = list("qiita") >>>str_list.sort(reverse=True) >>>print(str_list) ['t', 'q', 'i', 'i', 'a']

It seems that you should say.

What is a sorted function and how to use it

According to the dot blog "The sorted function is one of Python's built-in functions that sorts (sorts) elements in an object that has multiple elements such as lists, tuples, dictionaries, sets, and strings, and returns them in a new list." Is written, for example

>>>x = (5, 8, 4, 1, 3, 2, 7, 6) >>>y = sorted(x, reverse=True) >>>print(y)

Even if you enter

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

Seems to be output. To make tuples

>>>x = (5, 8, 4, 1, 3, 2, 7, 6) >>>y = tuple(sorted(x, reverse=True)) >>>print(y)

If so, it seems to be tupled and output. Also, if you use the sorted function in the dictionary

>>>sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}) [1, 2, 3, 4, 5]

It seems that the elements of the dictionary are listed and output.

What's the difference

By the way, most of the answers have been given so far, so I will write them in a comprehensive form. -The sort method can be applied only to the list, and the original list is used as it is for sorting. -On the other hand, the sorted function is effective for iterable ones, and after sorting, put elements in a new list. There was a difference like that. It's a digression from here, For the sort method and sorted function, if you specify key = function as an argument, It seems that sorting is performed based on the value of the function as a comparison standard. For example, according to the Python 3.9 documentation

Example of case-insensitive string comparison:

>>>sorted("This is a test string from Andrew".split(), key=str.lower) ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

Other

>>>student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ] >>>sorted(student_tuples, key=lambda student: student[2]) # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

It seems that you can also use it as described above. (capture) If key = function name, it seems that the function of the function is first executed for each element of the iterable object, and then the function is sorted. For example, in the above two examples, In the former, it seems that each element of the character string listed first is replaced with all lowercase letters and then sorted. (However, it returns to the original element at the time of output.) Therefore, it seems that the sorting will be carried out regardless of the size. Then, since the latter uses a lambda expression, that is,

>>>def ~~(student): return student[2]

Therefore, each element of the above list (that is, the above tuple) is assigned to the actual argument of this anonymous function, and the value whose index number is 2 is returned as the return value, and then that is used as the comparison target. Sort. One thing I wondered here. "If the above index numbers are the same, what is the next comparison? 』
Can anyone please teach me?

Huh. I wrote it for the first time, but it takes time and physical strength. Next time, I would like to write if there is something that interests me. If you have any mistakes, please let us know.

Thank you for staying with us on a long and long journey to the end. Also thank you next time.

Recommended Posts

Difference between sort and sorted (memorial)
[Python] Difference between sorted and sorted (Colaboratory)
Difference between process and job
Difference between "categorical_crossentropy" and "sparse_categorical_crossentropy"
Difference between np.array and np.arange
Difference between MicroPython and CPython
Difference between ps a and ps -a
Difference between return and print-Python
Difference between Ruby and Python split
Difference between java and python (memo)
Difference between list () and [] in Python
Difference between SQLAlchemy filter () and filter_by ()
Difference between == and is in python
Memorandum (difference between csv.reader and csv.dictreader)
(Note) Difference between gateway and default gateway
Difference between Numpy randint and Random randint
Difference between python2 series and python3 series dict.keys ()
[Python] Difference between function and method
Difference between SQLAlchemy flush () and commit ()
Python --Difference between exec and eval
[Python] Difference between randrange () and randint ()
difference between statements (statements) and expressions (expressions) in Python
[Django ORM] Difference between values () and only ()
Difference between PHP and Python finally and exit
Difference between @classmethod and @staticmethod in Python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
Difference between linear regression, Ridge regression and Lasso regression
[Python] Difference between class method and static method
Difference between docker-compose env_file and .env file
[Python Iroha] Difference between List and Tuple
[python] Difference between rand and randn output
speed difference between wsgi, Bottle and Flask
Difference between numpy.ndarray and list (dimension, size)
Difference between ls -l and cat command
Difference and compatibility verification between keras and tf.keras # 1
What is the difference between `pip` and` conda`?
Difference between using and import on shield language
[python] Difference between variables and self. Variables in class
About the difference between "==" and "is" in python
About the difference between PostgreSQL su and sudo
What is the difference between Unix and Linux?
Python> Sort by number and sort by alphabet> Use sorted ()
Consideration of the difference between ROC curve and PR curve
The rough difference between Unicode and UTF-8 (and their friends)
Center difference and forward difference
Can BERT tell the difference between "candy (candy)" and "candy (rain)"?
Between parametric and nonparametric
Difference between Ruby and Python in terms of variables
What is the difference between usleep, nanosleep and clock_nanosleep?
Difference between Numpy (n,) and (n, 1) notation [Difference between horizontal vector and vertical vector]
Difference between return, return None, and no return description in Python
How to use argparse and the difference between optparse
What is the difference between a symbolic link and a hard link?
Python module num2words Difference in behavior between English and Russian
Python> Difference between inpbt and print (inpbt) output> [1. 2. 3.] / array ([1., 2., 3.], dtype = float32)
Understand the difference between cumulative assignment to variables and cumulative assignment to objects
List concatenation method in python, difference between list.extend () and “+” operator
Difference between SQLAlchemy back_populates and backref and when neither is used
The difference between foreground and background processes understood by the principle
Correspondence between pandas and SQL