[Algorithm x Python] How to use the list

I will write about algorithms and Python.

table of contents 0. What is an algorithm?

  1. What is a list?
  2. How to use the list

0. What is an algorithm?

It is a procedure for calculating and working. We aim to process ** efficiently ** in a short time **.

1. What is a list?

It is one of ** data structures ** and has a structure in which data are arranged in a straight line. It is often used in algorithms that handle large amounts of data. The list is ** easy to add and delete data **, but it takes time to access.

** Point **: Data structure When data is put into the memory of a computer, the order and positional relationship of the data are defined.

1-0. Python and list

In Python, lists are often used rather than arrays. The element of the list can be ** any Python object **. And the element type is ** not need to be unified **.

** Point **: Array One of the ** data structures **, which arranges data in a row. While it's easy to access the data, it's time-consuming to add or remove.

2. How to use the list

2-0. Creating a list

◯ Create a list in the form of list name = [].

#Create an empty list with no elements
color_list = []

Of course, you can also add elements from the beginning. In that case, put ** elements separated by commas as shown below.

#Put elements in the list
color_list = ['Red','Yellow','Green']

2-1. Make a list from other data types

Creating a list using the list () function

◯ You can list other objects by using the list () function.

#Convert a string to a list
list('book')
#When a string is listed, each character becomes an element of the list.
['b','o','o','k']

Creating a list using the split () function

◯ You can use the split () function to split a string into a list based on some separator string.

#Put the contents in the object birthday
birthday = '29/9/1993'
#Decide where you want to split(This time slash= /)To divide
birthday.split('/')
['9','29','1993']

2-2. Acquisition of elements

Getting elements using [offset]

◯ You can retrieve elements from the list using [offset]. Note that the offset of the leftmost element is 0.

#Create a list with strings as elements
color_list = ['Red','Yellow','Green']
#Gets the elements of the list specified by the offset
print(color_list[0])
print(color_list[2])
print(color_list[-1])
'Red'
'Green'
'Green'

If the number of elements in the list is large, you can specify the elements from the back of the list using an index such as -1, -2 ....

In this case, if the character string 'Green' is specified from the left using an offset, it will be color_list [2], and it will be specified using a negative index from the end of the list. In the case, it becomes color_list [-1].

Get elements and indexes using the enumerate () function

◯ You can get elements and indexes efficiently by using the enumerate () function.

enumerate0.py


#object(variable)Substitute a string for s
s = 'TOKYO'
#Elements efficiently using for loops(item)And its index(offset)To get
for (offset,item) in enumerate(s):
    print(item,'Index is',offset)
Index of T is 0
Index of O is 1
K index is 2
Y index is 3
O index is 4

enumerate1.py


#Make a list of color elements
color_list = ['Red','Yellow','Green','Blue','White']

#Elements from the list(String)And get its index
for i,color in enumerate(color_list):
    print(color,'Is',i,'Second')
Red is 0th
Yellow is the first
Green is second
Blue is the third
White is fourth

Getting multiple elements using slices

◯ You can extract multiple elements using slices. A slice of the list is also a list.

When getting the elements with [start: end], get the elements from start to ** end-1 ** by offset. ("2-3. Update Elements" has a detailed description of slices.)

alphabet = ['A','B','C','D','E']

slice0.py


#Offset, 0 to 2(3-1)You can get the elements of.
alphabet[0:3]
['A', 'B', 'C']

Getting multiple elements using steps

slice1.py


#Two steps from the top of the list(Every other)Get the element with
alphabet[::2]
['A', 'C', 'E']

◯ You can get the element from the end by using minus

slice2.py


#Two steps from the end of the list(Every other)Get the element with
alphabet[::-2]
['E', 'C', 'A']

◯ You can reverse the order of the elements in the list by applying the steps ↓

slice3.py


#Get list elements in order from the end
alphabet[::-1]
['E','D','C','B','A']

2-3. Update elements

Rewriting elements using [Offset]

#Make a list of Asian country names
asian_countries = ['China','India','Japan']

#To the second element from the left in the list'Russia'Substitute
asian_countries[1] = 'Russia'
print(asian_countries)

Updating elements with slices

◯ You can use slices to get elements in a specified range and replace them.

[:] Get elements from beginning to end [start:] Get the elements from the start offset to the end [: end] Get the elements from the beginning to the end-1 offset [start: end] Get elements from start offset to end-1 offset [start: end: step] From the start offset, get the elements up to the end-1 offset for each step.

Update elements using [:]

◯ Update the entire list.

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

#Get and replace all elements from beginning to end.
numbers[:] = ['one','two','three','etc']
print(numbers)
['one','two','three','etc']
Update elements using [start:]

◯ Replaces the elements from the specified location to the end. It is an image like substitution.

numbers = ['one','two','three','etc']

#Replace by specifying the element from offset 3 to the end
numbers[3:] = ['four','five','six']
print(numbers)
['one', 'two', 'three', 'four', 'five', 'six']
Updating elements using [: end]

◯ Get and replace the elements from the beginning to end-1.

numbers = [4,5,6,7,8,9]

#From the beginning end-From 1, that is, 0-Gets and replaces elements in the range of 1.
#-List in spaces from 1 to 0[1,2,3]It is an image to substitute.
numbers[:0] = [1,2,3]
print(numbers)
[1,2,3,4,5,6,7,8,9]
Update elements using [start: end]

◯ Get the range of start <= element <end with the offset and replace it.

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

#Offset, 0 to 2(3-1)Gets and replaces elements in the range up to.
numbers[0:3] = ['one','two','three']
print(numbers)
['one', 'two', 'three', 4, 5, 6, 7, 8, 9]
Update elements using [start: end: step]

◯ Get and replace elements for each step in the range from start to end-1.

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

#Get elements every 3 to 3 offsets and list them['three','six','nine']Replace with.
numbers[2::3] = ['three','six','nine']
print(numbers)
[1, 2, 'three', 4, 5, 'six', 7, 8, 'nine']

2-4. Add element

Adding elements using the append () function

◯ Add an element at the end.

ex0.py


#Make a list of Asian country names
asian_countries = ['China','India','Japan']

#Add an element at the end
asian_countries.append('Russia')
print(asian_countries)
['China', 'India', 'Japan','Russia']

Adding elements using the insert () function

◯ Add an element to the specified location using the offset.

asian_countries = ['China','India','Japan']

#String at offset 2 in the list'Indonesia'To add.
asian_countries.insert(2,'Indonesia')
['China', 'India', 'Indonesia', 'Japan']

2-5. Deleting elements

Deleting elements using del and [offset]

◯ del List name Deletes the specified element in the form of [offset].

asian_countries = ['China','India','Indonesia','Japan']

#del is a Python statement, assignment(=)Something like the opposite of.
#del is not a method
del asian_countries[2]
print(asian_countries)
['China','India','Japan']

Remove elements using the remove () function

◯ Use this when you do not know where the element you want to erase is.

asian_countries = ['China','India','Indonesia','Japan']

#Specify an element and delete it
asian_countries.remove('Indonesia')
print(asian_countries)
['China','India','Japan']

Deleting elements using the pop () function

◯ You can take an element from the list and delete it at the same time.

asian_countries = ['China','India','Indonesia','Japan']

#Specify an element and delete it
print(asian_countries.pop(2))
Indonesia
print(asian_countries)
['China','India','Japan']

2-6. Sorting elements

Sorting using the sort () function

◯ Sort the list on the spot. The default is ascending order. For strings, it is in alphabetical order.

alphabet = ['A','E','D','C','B']

#All strings to be sorted must be of the same type
alphabet.sort()
print(alphabet)
['A', 'B', 'C', 'D', 'E']

Sorting using the sorted () function

◯ Copy the list and sort it. So the original of the list will not change.

#Integers and floating point numbers can be sorted even if they are mixed
numbers = [ 2 , 1.5 , 1 , 0 , 0.5 , 2.5]

#New list sorted_Make numbers
#Substitute a sorted number list
sorted_numbers = sorted(numbers)

print('sorted_numbers =' , sorted_numbers)
print('numbers =' , numbers)
sorted_numbers = [0, 0.5, 1, 1.5, 2, 2.5]
numbers = [2, 1.5, 1, 0, 0.5, 2.5]

2-7. List of lists

◯ Python lists can have Python objects as elements. Therefore, the list itself can be treated as an element of other lists.

#Make a list of country names
asia = ['China','India','Indonesia']
americas = ['USA','Brazil','Mexico']
africa = ['Nigeria','Ethiopia','Egypt']
#Create a list that includes a list
countries = [asia,americas,africa,'Japan']

ex0.py


#Display a list that contains a list
print(countries)
[['China', 'India', 'Indonesia'], ['USA', 'Brazil', 'Mexico'], ['Nigeria', 'Ethiopia', 'Egypt'], 'Japan']

ex1.py


#Specify the element in the list by offset
print(countries[0])
['China', 'India', 'Indonesia']

◯ Get the element of offset 2 in the element of offset 1 (americas list) in the countries list.

ex2.py


#Specify the element in two steps
print(countries[1][2])
Mexico

2-8. Join list

Joining lists using the extend () function

◯ Use the extend () function to combine the two lists. All the elements in the list are in one list.

list1 = ['a','b','c']
list2 = ['d','e','f']

#Combine two lists into a new list
list1.extend(list2)
print(list1)
['a', 'b', 'c', 'd', 'e', 'f']

Combine lists using + =

Use ◯ ** + = ** to combine the two lists.

list_a = [1,2,3]
list_b = [4,5,6]

#Combine two lists into a new list
list_a.extend(list_b)
print(list_a)
[1,2,3,4,5,6]
list_a = [1,2,3]
list_b = [4,5,6]

#List is added to other list as one element
list_a.append(list_b)
print(list_a)
[1,2,3,[4,5,6]]

2-9. Other operations

Getting the offset using the index () function

◯ Used when you want to know the offset of an element.

asian_countries = ['China','India','Indonesia','Japan']

#String'Japan'Get the offset of
print(asian_countries.index('Japan'))
3

Test for the presence or absence of values using in

asian_countries = ['China','India','Indonesia','Japan']

#Know if a value is in the list
print('Japan' in asian_countries)
print('Russia' in asian_countries)
True
False

Calculation of the number of values using the count () function

#Assign a list of strings to the variable characters
characters = list('personal_computer')
print(characters)

['p', 'e', 'r', 's', 'o', 'n', 'a', 'l', '_', 'c', 'o', 'm', 'p', 'u', 't', 'e', 'r']

#In the list called characters'o'Find out how many are included
print(characters.count('o'))
2

Getting the length using the len () function

#Find out the number of elements in the list characters
print(len(characters))
17

Finally

Thank you for reading. Next, I would like to write a little more about the list. If you have any mistakes or improvements, please let us know.

Recommended Posts

[Algorithm x Python] How to use the list
[Python] How to use list 1
[Python] How to use list 3 Added
How to use list []
Summary of how to use Python list
[Blender x Python] How to use modifiers
How to use the C library in Python
python3: How to use bottle (2)
How to use the generator
How to use Python argparse
Python: How to use pydub
[Python] How to use checkio
[Python] How to use input ()
How to use the decorator
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
How to use the Raspberry Pi relay module Python
[Python] How to use the graph creation library Altair
[Introduction to Udemy Python3 + Application] 27. How to use the dictionary
[Introduction to Udemy Python3 + Application] 30. How to use the set
How to use the model learned in Lobe in Python
[Python] How to output the list values in order
Python: How to use async with
How to use the zip function
How to use the optparse module
[Python] How to use Pandas Series
How to use Requests (Python Library)
How to use SQLite in Python
[Python] How to import the library
How to use Mysql in python
How to use OpenPose's Python API
How to use ChemSpider in Python
How to use FTP with Python
Python: How to use pydub (playback)
How to use PubChem in Python
How to use python zip function
How to use the ConfigParser module
[Python] How to use Typetalk API
[python] How to use the library Matplotlib for drawing graphs
[Hyperledger Iroha] Notes on how to use the Python SDK
How to get the last (last) value in a list in Python
I didn't know how to use the [python] for statement
[Python] Summary of how to use pandas
[Introduction to Python] How to use class in Python?
How to use the Spark ML pipeline
How to install and use pandas_datareader [Python]
[Python] How to convert a 2D list to a 1D list
[Linux] How to use the echo command
How to use the Linux grep command
[Python] How to use import sys sys.argv
How to erase Python 2.x on Mac.
[Python] Organizing how to use for statements
Memorandum on how to use gremlin python
[Python2.7] Summary of how to use unittest
python: How to use locals () and globals ()
Python amateurs try to summarize the list ①
How to use __slots__ in Python class
How to use "deque" for Python data