[Python memo] Be careful when creating a two-dimensional array (list of lists)

0. Problem

__ Rows (n1) and columns (n2) are entered in the first row, and n2 columns. Or # are entered in the second and subsequent rows. Store the character strings on the second and subsequent lines n1 in a two-dimensional array. __

1. 1. Input data

Give the following input data as an example

3 5
#####
.#.#.
#.#.#

2. Code example


#Enter the rows and columns of the array to be created separated by spaces
in1 = input()
arr1=in1.split()

#Next to arr1 specified above[1]The character string for the column is arr1[0]Read line text
in2=[]
for i in range(int(arr1[0])):
    tmp1=input()
    in2.append(tmp1)
        
#The following two-dimensional array(arr1[0]Line arr1[1]Column)Create
arr2=[[''] * int(arr1[1]) for i in range(int(arr1[0]))]
arr3=[['']*int(arr1[1])]*int(arr1[0])

#Display the 2D array defined above
print(arr2)
print(arr3)

for i in range(int(arr1[0])):
    tmp2=in2[i]
    for j in range(int(arr1[1])):
        arr2[i][j]=tmp2[j:j+1]
        arr3[i][j]=tmp2[j:j+1]


print(arr2)
print(arr3)

3. 3. Output result

[['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', '']]
[['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', '']]
[['#', '#', '#', '#', '#'], ['.', '#', '.', '#', '.'], ['#', '.', '#', '.', '#']]
[['#', '.', '#', '.', '#'], ['#', '.', '#', '.', '#'], ['#', '.', '#', '.', '#']]

In the first and second lines, the initialized two-dimensional array data is displayed. What we pay attention to is the difference between the execution results of the 3rd and 4th lines `__.

The values in all the arrays of arr3 have been replaced with the data in the last row of input.

4. Verification

Refer to Initialize Python list (array) with arbitrary value / number of elements Add the following code to the above code.

print(arr2[0]==arr2[int(arr1[0])-1])
print(arr3[0]==arr3[int(arr1[0])-1])
False
True

Because the list of elements in arr3 are all treated as the same object It seems that when one list is updated, the other lists are updated with the same contents.

Conclusion

When declaring a two-dimensional array with initial values

List name = [[Initial value] * Number of columns for Arbitrary variable in range (number of rows)]

use.

Recommended Posts

[Python memo] Be careful when creating a two-dimensional array (list of lists)
A memo when creating a python environment with miniconda
Be careful when differentiating the eigenvectors of a matrix
A memo when creating a directed graph using Graphviz in Python
[Python] Be careful when using print
[Python] Creating a scraping tool Memo
Precautions when creating a Python generator
When creating a matrix in a list
Precautions when creating a two-dimensional array with all the same values
Be careful of LANG for UnicodeEncodeError when printing Japanese with Python 3
Addictive note: max (max (list)) must not be used when maxing the value of a 2D array
Display a list of alphabets in Python 3
[python] Get a list of instance variables
Be careful when adding an array to an array
[Python] Get a list of folders only
I made a function to see the movement of a two-dimensional array (Python)
A memo of a tutorial on running python on heroku
[python] Create a list of various character types
python memo: Treat lists as a set type
Make a copy of the list in Python
Rewriting elements in a loop of lists (Python)
Output in the form of a python array
A memo for creating a python environment by a beginner
[Python] Manipulating elements in a list (array) [Sort]
A memo of misunderstanding when trying to load the entire self-made module with Python3
[Caution] When creating a binary image (1bit / pixel), be aware of the file format!
[Grasshopper] When creating a data tree on Python script
A memo connected to HiveServer2 of EMR with python
[Python] Manipulation of elements in list (array) [Add / Delete]
How to write a list / dictionary type of Python3
Things to note when initializing a list in Python
Python: Get a list of methods for an object
Group by consecutive elements of a list in Python
A python regular expression, or a memo of a match object
Creating a list when the nomenclature is a fixed time
List of python modules
Python3 List / dictionary memo
When I got a list of study sessions in Python, I found something I wanted to make
[Python] How to make a list of character strings character by character
How to shuffle a part of a Python list (at random.shuffle)
A memo when face is detected with Python + OpenCV quickly
Get the number of specific elements in a python list
Since Python 1.5 of Discord, I can't get a list of members
[Python] A program that creates a two-dimensional array by combining integers
How to develop in a virtual environment of Python [Memo]
Be careful when assigning Series as a column to pandas.DataFrame
How to get a list of built-in exceptions in python
Python: Create a dictionary from a list of keys and values
A memo of writing a basic function in Python using recursion
Precautions that must be understood when building a PYTHON environment
Turn an array of strings with a for statement (Python3)
List of libraries to install when installing Python using Pyenv
[Python3] List of sites that I referred to when I started Python
Here's a summary of things that might be useful when dealing with complex numbers in Python
Python hand play (two-dimensional list)
Python memo (for myself): Array
Summary of Python3 list operations
Python list is not a list
Create a python numpy array
Multidimensional array initialization of list
[Python] Copy of multidimensional list