First, take a look at the program below (no need to write a program)
L = [] #Create an empty list L
print(L) #Output element of L
for i in range(10):
L.append(i) #Append element to list L with append method
print(L)
Execution result
[Execution result] </ font> [] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Briefly, an empty list ** L ** is created, and the elements of the empty list are output once with the ** print function **. (Of course it's empty) Then move into the for statement and use the ** append method ** to add ** L ** elements one by one. (The append method was explained earlier.)
Finally, the print function outputs the contents of the element.
However, you can also output this process in one line. There is a ** inclusion notation ** as a method, so I will explain it.
There are various comprehension notations, but they are described using the following description method.
[Calculation result by variable for variable in for repeat target]
There is a reason why it is described as "calculation result by variable", but I will explain it later. First, let's actually describe the same processing content as the above program in the inclusion notation. This time, enter the following code from ** Python Console **.
>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The list notation is enclosed in []. By writing like this, it is possible to create a list in one line without using the append method or variables.
I will explain the reason why it is called "calculation result by variable". For example, when printing values in 0.5 increments to the list, you cannot write ** range (0, 10, 0.5) **. (You cannot specify a decimal number for step)
Therefore, we use the comprehension notation. Actually, it is described as follows. Enter the following code from the ** Python Console **.
>>> [i * 0.5 for i in range(10)]
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
The result of this comprehension can also be assigned to a variable.
>>> ls = [i * 0.5 for i in range(10)]
>>> ls
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
You can create dictionaries as well as lists. Enter the following code from the ** Python Console **.
>>> Countries = ['Japan', 'Canada', 'China', 'America']
>>> {n[0:2] : n for n in Countries}
{'Ja': 'Japan', 'Ca': 'Canada', 'Ch': 'China', 'Am': 'America'}
This time it's a dictionary, so use {} instead of []. The first two characters of each element are used as keys. It is output by combining it with the value.
We have prepared exercises. Please try to solve it. Please use ** Python Console **. [1] Create a list of the results of squares of integers from 1 to 9 using comprehension notation. The results are as follows. [1, 4, 9, 16, 25, 36, 49, 64, 81]
This time I touched on the inclusion notation, but have you noticed it? Actually, I'm only using ** Python Console ** this time. Not much in other languages yet. The comprehension can be entered as a command. You can also use simple notation, so please use it.