sec02 - list Overview

list is a structure that can store multiple values in a single variable.

スポンサーリンク

Initialization of list

First, let's initialize the minimum list. Write the code as follows.

num_list = []

Assign empty square brackets ([]) to a variable. This is a list with zero elements.

A list does not necessarily need to have elements. After initializing it with zero elements, you can add elements using the append() method or the + operator. (The method for adding elements will be explained in detail in a dedicated lecture.)

A list can contain one or more elements. You can initialize a list as follows.

numbers = [1, 2, 3, 4, 5]
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
alphabets = ['a', 'b', 'c', 'd', 'e']
cities = ['Tokyo', 'New York', 'Paris', 'Rio de Janeiro', 'Cairo']

The above code initializes (1) a list of numbers, (2) a list of prime numbers, (3) a list of alphabets, and (4) a list of city names. Each element is separated by a comma (,).

Generally, lists are easier to understand and manage when they contain only one data type, such as a list of numbers or a list of strings. However, as shown in the following code, you can also create a list that contains different data types.

mixed = [1, 'two', 3.0, [4]]

The list in the above code contains the data types int, string, float, and list. As you can see, Python makes it easy to manage multiple types of data.

Extracting elements from a list

List elements are written in the same way as strings, using [n]. Let's try extracting the elements of the “mixed” variable from earlier.

mixed = [1, 'two', 3.0, [4]]
print(mixed[0])  # 1
print(mixed[1])  # 'two'
print(mixed[2])  # 3.0
print(mixed[3])  # [4]

As shown in the code above, you can retrieve elements one by one using indexes.

(Slicing lists will be explained in a separate lecture.)

スポンサーリンク

Number of elements in list - len() function

To check the number of elements in a list, use the len() function.

mixed = [1, 'two', 3.0, [4]]
print(len(mixed))  # 4

2D list

Python lists can contain other lists as elements. Embedding one data structure within another is called nesting.

Data with nested lists can be treated like data in rows and columns, so it is called a 2D list. Nesting can be done to any depth.

Lists and arrays

Some other programming languages refer to structures similar to lists as “arrays.” Therefore, even Python programmers may refer to nested lists as “2D arrays.” These terms are interchangeable and refer to the same thing.

Initialization of a 2D list is as follows.

multiplication_table = [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5], [0, 2, 4, 6, 8, 10], [0, 3, 6, 9, 12, 15], [0, 4, 8, 12, 16, 20], [0, 5, 10, 15, 20, 25]]

If there are many elements and the code becomes difficult to read, you can write the elements on separate lines as shown in the following code.

multiplication_table = [
    [0, 0, 0, 0, 0],
    [0, 1, 2, 3, 4, 5],
    [0, 2, 4, 6, 8, 10],
    [0, 3, 6, 9, 12, 15],
    [0, 4, 8, 12, 16, 20],
    [0, 5, 10, 15, 20, 25]
]

As shown above, when describing elements with line breaks, combining them with indentation (inserting spaces at the beginning of program lines) makes the code easier to read.

indentation

Python generally does not require indentation when writing code. If there are spaces at the beginning of a line where indentation is not allowed, an error will occur.

However, Python syntax rules require indentation in some cases. In other cases, such as this one, indentation is permitted to make the code easier to read.

Indentation is required in cases such as conditional branching (if) or repetitive processing (for/while), as well as when writing code inside a function. These will be explained in dedicated lectures, so you can learn them at that time.

Regarding “cases where indentation is allowed to make code easier to read,” we will explain this as needed in the Python 101 lectures, so please remember it as you go along.

The 2D list that was initialized earlier is now a ‘5x5 multiplication table’. Let's try outputting the results of ‘2x3’ and ‘4x5’.

multiplication_table = [
    [0, 0, 0, 0, 0],
    [0, 1, 2, 3, 4, 5],
    [0, 2, 4, 6, 8, 10],
    [0, 3, 6, 9, 12, 15],
    [0, 4, 8, 12, 16, 20],
    [0, 5, 10, 15, 20, 25]
]
answer_2x3 = multiplication_table[2][3]
answer_4x5 = multiplication_table[4][5]
print(f'2x3={answer_2x3}, 4x5={answer_4x5}')

When you run the above code, you will get the result “2x3=6, 4x5=20”. To retrieve elements from a 2D list, use the notation [n][m].

Using “2x3” as an example, first, you can retrieve the list [0, 2, 4, 6, 8, 10] corresponding to element number [2] from multiplication_table[2]. By specifying the element number [3] within the list [0, 2, 4, 6, 8, 10] retrieved earlier, you can extract the desired “6.” Therefore, by concatenating [2] and [3](multiplication_table[2][3]), you can obtain the result ‘6’ for “2x3.”

Examples of using list

As an example of using a list, we will explain the glob function. glob is a function that returns a list of folders and files existing in the specified directory. In this example, we will execute a simple code to obtain a list of folders/files existing directly under the C drive in Windows.

import glob
c_drive_list = glob.glob('c:/*')
print(c_drive_list)

When you run the above code, you should get a result similar to the one below. (The result may vary depending on your C drive environment. Since a large amount of data is returned, some data has been replaced with “...”.)

['c:/Documents and Settings',... 'c:/Program Files', 'c:/Program Files (x86)',... 'c:/ProgramData',... 'c:/Users', 'c:/Windows']

As in the example above, lists are used when returning large amounts of data. (Detailed explanations of the code will be provided in a separate lecture, so please focus on the results returned here.)

As a supplementary explanation, when displaying a list containing a large number of elements as shown above, printing the output results in long lines that can be difficult to read. In such cases, using the pprint function will output each element on a separate line, making the output easier to read.

import glob
from pprint import pprint

c_drive_list = glob.glob('c:/*')
pprint(c_drive_list)

The result output by pprint is as follows. Each element is output with a line break, making it easier to see what directories (folders/files) exist in the C drive.

['c:/Documents and Settings',
.....
 'c:/Program Files',
 'c:/Program Files (x86)',
 'c:/ProgramData',
.....
 'c:/Users',
 'c:/Windows']
pprint function

pprint is an abbreviation for “pretty-print,” and is a function that formats and outputs information such as list elements.

使い方ですが、from pprint import pprint行の後でpprint関数を実行します。次のような形式でコードを記述することで、使用することができます。

from pprint import pprint
pprint(variable)

Let's just remember the from pprint import pprint in the first line as it is. We will explain this in detail in the “Modules” lecture, but for now, just remember that it is a declaration to use the pprint function in Python.

スポンサーリンク