[Python] Manipulating elements in a list (array) [Sort]

Introduction

We have summarized the ** sorting ** methods that are important for working with lists. Basically, write the code and output result with the following code.

ex.py


code = 'code'
print(code)
# code(Output result)

Sort the list in ascending or descending order sort (), sorted ()

There are two ways to sort a list in ascending or descending order in Python: sort () and sorted (). Use sorted () if you want to sort strings and tuples.

· Sort (): sort the original list

** * Destructive processing that rewrites the original list itself. ** **

sort().py


org_list = [3, 1, 4, 5, 2]

org_list.sort()
print(org_list)
# [1, 2, 3, 4, 5]

#sort()Note that returns None.
print(org_list.sort())
# None

#The default is ascending order. If you want to sort in descending order, set the argument reverse to True.
org_list.sort(reverse=True)
print(org_list)
# [5, 4, 3, 2, 1]

sorted (): Generate a new sorted list

** * If you specify the list you want to sort in the argument, the sorted list is returned. Non-destructive processing that does not change the original list. ** **

sorted().py


org_list = [3, 1, 4, 5, 2]

new_list = sorted(org_list)
print(org_list)
# [3, 1, 4, 5, 2]
print(new_list)
# [1, 2, 3, 4, 5]

#The default is ascending order. If you want to sort in descending order, set the argument reverse to True.
new_list_reverse = sorted(org_list, reverse=True)
print(org_list)
# [3, 1, 4, 5, 2]
print(new_list_reverse)
# [5, 4, 3, 2, 1]

Sorting strings using sorted ()

If a character string is specified as an argument of the sorted () function, a ** list ** in which each character of the sorted character string is stored as an element is returned.

sorted()_.py


org_str = 'cebad'
print(org_str)
# cebad

new_str_list = sorted(org_str)
print(new_str_list)
# ['a', 'b', 'c', 'd', 'e']

#Join to concatenate a list of strings into a single string()Use the method.
new_str = ''.join(new_str_list)
print(new_str)
# abcde

#You can write them all together. If you want to sort in descending order, set the argument reverse to True.
new_str_reverse = ''.join(sorted(org_str, reverse=True))
print(new_str_reverse)
# edcba

Reverse (), reversed () to sort lists and strings in reverse order

There are ways to sort the elements of a list in reverse order in Python using reverse (), reversed () and slices. Use reversed () or slices if you want to sort strings or tuples in reverse order.

· Reverse (): Sort the original list in reverse order

** * Destructive processing that rewrites the original list itself. ** **

sort().py


org_list = [1, 2, 3, 4, 5]

org_list.reverse()
print(org_list)
# [5, 4, 3, 2, 1]

#reverse()Note that returns None.
print(org_list.reverse())
# None

-Reversed (): Generates an iterator to retrieve in reverse order

** * reversed () returns an iterator that retrieves the elements in reverse order. Non-destructive processing that does not change the original list. ** **

sort().py


org_list = [1, 2, 3, 4, 5]

reverse_iterator = reversed(org_list)
print(org_list)
# [1, 2, 3, 4, 5]

#reversed()Note that returns an iterator instead of a list. list()Convert the iterator to a list with.
new_list = list(reversed(org_list))
print(new_list)
# [5, 4, 3, 2, 1]

・ Sort in reverse order by slice

ex.py


org_list = [1, 2, 3, 4, 5]
new_list = org_list[::-1]
print(new_list)
# [5, 4, 3, 2, 1]

org_str = 'abcde'
new_str = org_str[::-1]
print(new_str)
# edcba

Finally

I would be grateful if you could tell me if there is any other solution.

Recommended Posts

[Python] Manipulating elements in a list (array) [Sort]
Sort list elements in a specified order in Python
Randomly select elements from list (array) in python
[Python] Manipulation of elements in list (array) [Add / Delete]
Group by consecutive elements of a list in Python
[python] Manage functions in a list
Delete multiple elements in python list
Sort and output the elements in the list as elements and multiples in Python.
Get the number of specific elements in a python list
Display a list of alphabets in Python 3
[Python] Combine all the elements in the array
Sorted list in Python
[Python] Sort the list of pathlib.Path in natural sort
How to clear tuples in a list (Python)
Bubble sort in Python
Filter List in Python
Make a copy of the list in Python
Rewriting elements in a loop of lists (Python)
Get only the subclass elements in a list
[Memo] Python3 list sort
View drug reviews using a list in Python
Extract every n elements from an array (list) in Python and Ruby
List find in Python
Custom sort in Python3
Output in the form of a python array
How to sort by specifying a column in the Python Numpy array.
How to remove duplicate elements in Python3 list
Extract elements (using a list of indexes) in a NumPy style from a Python list / tuple
Things to note when initializing a list in Python
[Python] Outputs all combinations of elements in the list
Take a screenshot in Python
Quicksort an array in Python 3
Create a function in Python
Empty multidimensional array in python
Naturally sort Path in Python
python in mongodb in descending sort
Python list is not a list
Create a python numpy array
Draw a heart in Python
Sort by date in python
[Python] Leave only the elements that start with a specific character string in the array
How to check in Python if one of the elements of a list is in another list
Make sure all the elements in the list are the same in Python
Create a list in Python with all followers on twitter
How to swap elements in an array in Python, and how to reverse an array.
Developed a library to get Kindle collection list in Python
How to get a list of built-in exceptions in python
Create a new list by combining duplicate elements in the list
Python> Get a list of files in multiple directories> Use glob | Sort by modification time
Extract multiple list duplicates in Python
Maybe in a python (original title: Maybe in Python)
Write a binary search in Python
python web scraping-get elements in bulk
Output 2017 Premium Friday list in Python
Hit a command in Python (Windows)
Create a DI Container in Python
Draw a scatterplot matrix in python
ABC166 in Python A ~ C problem
Write A * (A-star) algorithm in Python
python / Make a dict from a list.
Sort large text files in Python